Rust中两个字符串引用函数的区别及报错咨询
Rust引用参数的函数定义差异与报错解析
我是Rust新手,阅读官方文档后仍无法理解Rust引用的工作原理,现咨询以下两个函数的区别:
fn some_function1(&s: String) -> usize { s.len() }
和
fn some_function2(s: &String) -> usize { s.len() }
运行测试代码时出现类型不匹配错误,测试代码及报错信息如下:
测试代码
fn main(){ let s = String::from("hello"); let z = String::from("World"); println!("length of s is: {}", some_function1(s)); println!("length of z is: {}", some_function2(z)); } fn some_function1(&s: String) -> usize{ s.len() } fn some_function2(z: &String) -> usize{ z.len() }
报错信息
rustc /tmp/lHkDSH6rQp/main.rs error[E0308]: mismatched types --> /tmp/lHkDSH6rQp/main.rs:8:48 | 8 | println!("length of z is: {}", some_function2(z)); | -------------- ^ | | | expected `&String`, found struct `String` help: consider borrowing here: `&z` arguments to this function are incorrect | note: function defined here --> /tmp/lHkDSH6rQp/main.rs:15:4 | 15 | fn some_function2(z: &String) -> usize{ | ^^^^^^^^^^^^^^ ---------- error[E0308]: mismatched types --> /tmp/lHkDSH6rQp/main.rs:11:19 | 11 | fn some_function1(&s: String) -> usize{ expected due to this | | expected struct `String`, found reference | note: expected struct `String` found reference `&_` help: to take parameter `s` by reference, move `&` to the type | 11 - fn some_function1(&s: String) -> usize{ 11 + fn some_function1(s: &String) -> usize{ | error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`.
一、两个函数的核心差异
some_function1的写法完全错误:
Rust函数参数的标准格式是参数名: 类型,&s: String属于混淆了模式匹配和类型声明的错误写法。这里的&s模式要求传入一个引用类型的值,但参数声明的类型是String(非引用),两者类型不兼容,编译器直接报错。some_function2的写法是标准引用传递:z: &String表示参数z的类型是不可变引用&String,函数接收的是对String的引用,而非直接获取String的所有权,这是Rust中传递引用的正确方式。
二、报错原因与修正方案
1. some_function2(z)的调用错误
函数some_function2要求传入&String类型,但调用时传入的是String类型的z。只需通过&z创建不可变引用,修改调用代码:
println!("length of z is: {}", some_function2(&z));
2. some_function1的定义错误
&s: String的写法逻辑混乱,正确的引用参数写法应将&放在类型声明部分,修改函数定义:
fn some_function1(s: &String) -> usize{ s.len() }
同时调用时也要传入引用,将some_function1(s)改为some_function1(&s)。
三、修正后的完整代码
fn main(){ let s = String::from("hello"); let z = String::from("World"); println!("length of s is: {}", some_function1(&s)); println!("length of z is: {}", some_function2(&z)); } fn some_function1(s: &String) -> usize{ s.len() } fn some_function2(z: &String) -> usize{ z.len() }
内容的提问来源于stack exchange,提问作者Thomas Jasper
相关产品推荐
相关产品推荐

