【发布时间】:2026-01-28 15:30:01
【问题描述】:
我有以下代码,
impl<T: Debug + Into<String> + Clone> TryFrom<Vec<T>> for Positionals {
type Error = &'static str;
fn try_from(mut vec: Vec<T>) -> Result<Self, Self::Error> {
let mystr: String = vec.get(0).unwrap().into();
而该代码正在产生此错误,
error[E0277]: the trait bound `String: From<&T>` is not satisfied
--> bin/seq.rs:21:43
|
21 | let mystr: String = vec.get(0).unwrap().into();
| ^^^^ the trait `From<&T>` is not implemented for `String`
|
= note: required because of the requirements on the impl of `Into<String>` for `&T`
help: consider introducing a `where` bound, but there might be an alternative better way to express this requirement
我很困惑为什么这会产生错误,因为我在Vec<T> 上有一个特征绑定,因此T 必须实现Into<String>,还需要什么?我不明白这是为什么,我删除了into(),我明白了
let mystr: String = vec.get(0).unwrap();
------ ^^^^^^^^^^^^^^^^^^^ expected struct `String`, found `&T`
如何将Vec<T> 中的T 转至String?我之所以做Vec<T>而不是Vec<String>是因为我也想支持Vec<&str>。
【问题讨论】:
标签: string rust type-conversion traits