gpt4 book ai didi

rust - 注释生命周期/确定方法中字符串所有权的正确方法?

转载 作者:行者123 更新时间:2023-12-03 11:43:43 24 4
gpt4 key购买 nike

只是从我在Rust中的冒险开始,并试图找出创建和返回枚举的正确方法,该枚举应该拥有通过传递给该方法的String创建的&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())
}
}

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

最佳答案

正如其他人在评论中所说的那样,最简单的方法是在各处使用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

关于rust - 注释生命周期/确定方法中字符串所有权的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59240479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com