Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 13.2.2 节 普通函数调用参数的协变、逆变和不变 第1版 第4次印刷 #295

Open
zydxhs opened this issue May 12, 2020 · 3 comments
Labels
第十三章 第十三章
Milestone

Comments

@zydxhs
Copy link

zydxhs commented May 12, 2020

页码与行数

  • 第494页
  • 第2行

普通的函数调 用 ,参数是不变。当参数 需要&’ static s衍 类型时,不能用&由代替它。
但是函数的返回值是协变 , 当返回值是&str 的时候,可以返回&’ static str 类型 的值作
为替代 。

issue#30 指出参数是不变。
而我的测试,函数分别为 &str, &'a str, &'static str,实参分别为 &str 和 &'static str,三个函数调用都没问题。

这应该怎么理解?感觉既像是协变,又像逆变?
PlayGround 地址: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e341ad718d83fdea7b2263263e930c8d

@mzji
Copy link

mzji commented May 13, 2020

关于逆变和协变,可以参考 nomiconC# 的相关文档

@acodercat
Copy link

这是因为 &str的生命周期始终都是'static, 你换成i32就会报错了

@zydxhs
Copy link
Author

zydxhs commented May 13, 2020

3ks @mzji 我找时间看看。
用 i32 类型测试了下,普通的函数调用,更像是协变:

fn bar(s: &i32){
    println!("bar: {}", s);
}

fn bar3(s: &'static i32){
    println!("bar3: {}", s);
}

static INT32: i32 = 23;

fn main() {
    let i: i32 = 12;
    bar(&i);
    bar(&INT32);

    bar3(&INT32);
    //bar3(&i); 这一行报错
}

@ZhangHanDong ZhangHanDong added the 第十三章 第十三章 label May 15, 2020
@ZhangHanDong ZhangHanDong added this to the 第二版 milestone Jun 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
第十三章 第十三章
Projects
None yet
Development

No branches or pull requests

4 participants