【问题标题】:The correct way to annotate lifetimes/ determine ownership of strings in a method?注释生命周期/确定方法中字符串所有权的正确方法?
【发布时间】:2019-12-08 22:27:48
【问题描述】:

刚开始我在 Rust 中的冒险并试图找出正确的方法来创建和返回一个枚举,该枚举应该拥有一个 &str 字符串切片的所有权,该切片是从传递给该方法的字符串创建的。我认为生命周期注释本身并不能解决问题,因为无论如何原始字符串参数将超出函数块末尾的范围。任何帮助将不胜感激。

pub enum PubSubMessage {
    // For now I won't worry about subbing/unsubbing to an array of channels
    SUBSCRIBE { channel: &str },
    UNSUBSCRIBE { channel: &str },
    PUBLISH { channel: &str, msg: &str},
    PSUBSCRIBE { pattern: &str },
    PUNSUBSCRIBE { pattern: &str},
}

pub fn parse_message(msg: String) -> Result<PubSubMessage, String> {
    let msg_contents: Vec<&str> = msg.split(" ").collect();

    return match msg_contents.as_slice() {
        ["SUBSCRBE", channel] => Ok(PubSubMessage::SUBSCRIBE { channel }),
        ["UNSUBSCRIBE", channel] => Ok(PubSubMessage::UNSUBSCRIBE { channel }),
        ["PUBLISH", channel, msg] => Ok(PubSubMessage::PUBLISH { channel, msg }),
        _ => Err("Could not parse ws message.".to_string())
    }
}

我得到的当前编译器错误只是枚举定义需要生命周期参数。

【问题讨论】:

标签: rust


【解决方案1】:

正如其他人在 cmets 中所说,最简单的方法是在任何地方使用String。话虽这么说,如果您想避免额外的副本和分配,您可以将拥有该字符串的责任推到调用链更高的位置。如果您想这样做,您将需要更改您的函数签名,以便它借用msg 而不是取得所有权,并添加所需的生命周期参数。像这样的:

pub enum PubSubMessage<'a> {
    // For now I won't worry about subbing/unsubbing to an array of channels
    SUBSCRIBE { channel: &'a str },
    UNSUBSCRIBE { channel: &'a str },
    PUBLISH { channel: &'a str, msg: &'a str},
    PSUBSCRIBE { pattern: &'a str },
    PUNSUBSCRIBE { pattern: &'a str},
}

pub fn parse_message<'a> (msg: &'a str) -> Result<PubSubMessage<'a>, String> {
    let msg_contents: Vec<_> = msg.split(" ").collect();

    return match msg_contents.as_slice() {
        ["SUBSCRBE", channel] => Ok(PubSubMessage::SUBSCRIBE { channel }),
        ["UNSUBSCRIBE", channel] => Ok(PubSubMessage::UNSUBSCRIBE { channel }),
        ["PUBLISH", channel, msg] => Ok(PubSubMessage::PUBLISH { channel, msg }),
        _ => Err("Could not parse ws message.".to_string())
    }
}

Playground

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 2021-04-04
    • 2013-07-25
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多