如何拿返回值,如何不传递所有权就更改原值?如果想操作更改元变量要怎么做呢?
分别执行以下go代码:
go
func main() {
var a = 10
//calc1(a)
//a = calc_return(a)
calc2(&a)
a = 100
calc3(&a)
fmt.Println(a)
}
func calc1(num int) {
num += num
}
func calc_return(num int) int {
num += num
return num
}
func calc2(num *int) {
*num += *num
}
func calc3(num *int) {
*num += *num
}
rust代码:
rust
use std::string;
fn main() {
let mut s1 = String::from("learn rust");
s1 = foo_return(s1);
println!{"{s1}"};
}
fn foo_return(s:String)->String{
println!{"{s}"};
s
}
rust
use std::string;
fn main() {
let mut s1 = String::from("learn rust");
// foo1(s1);
// foo2(&s1);
foo3(&mut s1);
println!{"{s1}"};
foo3(&mut s1);
}
fn foo1(s:String){
println!{"{s}"};
}
fn foo2(s:&String){
println!{"{s}"};
}
fn foo3(s:&mut String){
s.push_str(",you can be 666");
println!{"{s}"};
}
自己去体会其中的不同之处