在结构中存储& str时,“缺少生命周期说明符”是什么意思?

时间:2015-11-02 19:19:20

标签: rust

我正在尝试编写类似Excel的数据结构:

use std::collections::HashMap;

struct Excel {
    columns: HashMap<&str, Vec<f64>>,
}

fn main() {}

但是我收到了一个错误:

error[E0106]: missing lifetime specifier
 --> src/main.rs:4:22
  |
4 |     columns: HashMap<&str, Vec<f64>>,
  |                      ^ expected lifetime parameter

有人可以帮我理解发生了什么吗?

1 个答案:

答案 0 :(得分:20)

&#34;缺少生命周期说明符&#34;意味着在结构定义中,您还没有告诉它允许对字符串切片的引用保留多长时间。为了使您的代码安全,它必须至少与结构一样长。

您需要在结构上定义一个生命周期参数,并将其用于字符串切片。

func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) {

    if Leagues.count > 0 {
        var myLeague: [AnyObject] = [AnyObject]()
        for eachleague in Leagues {
            myLeague.insert(eachleague.LeagueID, atIndex: 0)
        }

       let tagSet: NSSet = NSSet(array: myLeague)

        let hub : SBNotificationHub = SBNotificationHub(connectionString: gEndPointName, notificationHubPath: gHubName)

        hub.registerNativeWithDeviceToken(deviceToken, tags: tagSet as! Set<NSObject>) { (error) -> Void in
            if (error != nil){
                print("Error registering for notifications: %@", error);
            }
        }
    }
}

这表示字符串切片(struct Excel<'a> { columns: HashMap<&'a str, Vec<f64>> } 键)具有由HashMap结构的用户参数化的一些生命周期。生命周期是Rust的关键特征之一。您可以在Rust documentation中了解有关生命周期的更多信息。

通常,定义拥有该字符串的结构更简单。然后,您可以使用Excel

String