You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何向函数传递字符串向量?

Rust函数参数中字符串向量类型声明错误的解决方法

问题原因

函数参数位置必须声明类型,但你写的vec![String]是用于创建Vec<String>实例的宏表达式,并非类型,这直接导致编译器抛出“expected type”错误。

你尝试的其他写法也存在问题:

  • Vec!是无效语法,Vec是标准库提供的容器类型,无需添加感叹号
  • String::String写法错误,String本身就是合法的类型名称,不需要通过::重复引用

正确代码示例

fn myfn(svect: Vec<String>) -> &'static str {
    "A string will be created from svect and returned."
}

额外说明

如果后续你需要让函数返回基于输入svect的字符串引用(而非静态字符串),则需要为返回值添加生命周期注解,比如:

fn myfn<'a>(svect: &'a Vec<String>) -> &'a str {
    svect.get(0).unwrap_or("")
}

内容的提问来源于stack exchange,提问作者rnso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:17:02