gpt4 book ai didi

rust - 尽管我实现了 `&str: From`,但 trait bound `From<&str> for MyType` 并不满足

转载 作者:行者123 更新时间:2023-11-29 08:09:58 26 4
gpt4 key购买 nike

我尝试在 FromInto 的帮助下实现游程编码。我的想法是我将只实现 from 并免费获得 into 实现。

extern crate regex;

use regex::Regex;

struct RLE(pub String);

impl<'a> From<&'a str> for RLE {
fn from(s: &str) -> Self {
let reg = Regex::new(r"(\d*)([\w\s])").unwrap();
let mut accum = String::new();
for c in reg.captures_iter(s) {
let n = c.get(1).unwrap().as_str().parse::<usize>().unwrap_or(1);
let c = c.get(2).unwrap().as_str();
accum.push_str(&c.repeat(n));
}
RLE(accum)
}
}

decode("2ab3c") => "aabccc"

pub fn decode(s: &str) -> String {
let RLE(string) = RLE::from(s);
string
}

encode("aabccc") => "2ab3c"

pub fn encode(s: &str) -> String {
let string: &'static str = RLE(s.to_string()).into();
string.to_string()
}

但是我得到以下错误:

error[E0277]: the trait bound `&str: std::convert::From<RLE>` is not satisfied
--> src/main.rs:26:51
|
26 | let string: &'static str = RLE(s.to_string()).into();
| ^^^^ the trait `std::convert::From<RLE>` is not implemented for `&str`
|
= note: required because of the requirements on the impl of `std::convert::Into<&str>` for `RLE`

我做错了什么?

最佳答案

你搞反了。 From<&str> for RLE不能可能用于执行 RLE&str转换。这就像使用 recipie 烤蛋糕,将其解构成其组成成分。

From<&str> for RLE暗示 Into<RLE> for &str 的存在.这意味着你可以做 a_str.into()而不是 RLE::from(a_str) .您可以通过查看 the documentation for Into 来解决这个问题,其中列出了以下实现:

impl<T, U> Into<U> for T where U: From<T>

如果您将类型替换为您的 From实现(使用 U = RLET = &str ),你得到:

impl Into<RLE> for &str where RLE: From<&str>

你想用 REL(s.to_string()).into() 做什么需要 impl Into<&str> for RLE .

关于rust - 尽管我实现了 `&str: From<MyType>`,但 trait bound `From<&str> for MyType` 并不满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44353117/

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