Cache { -6ren">
gpt4 book ai didi

generics - "Expected type parameter, found integer"从函数调用但不是从 main 调用

转载 作者:行者123 更新时间:2023-12-03 11:43:38 24 4
gpt4 key购买 nike

struct Cache<T> {
key: String,
val: T
}

impl<T> Cache<T> {
fn new(k: String, v: T) -> Cache<T> {
Cache { key: k, val: v }
}

fn update(&mut self, v: T) {
self.val = v;
}
}

fn increment<T>(cache: &mut Cache<T>, v: T) {
cache.update(v);
}

fn main() {
let mut c = Cache::new("akshay".to_string(), 21);
c.update(25);
println!("c = {}", c.val);
increment(&mut c, 30);
println!("c = {}", c.val);
}

这个例子工作得很好。但如果我改变 cache.update(v);cache.update(25);increment函数,我收到以下错误:
cache.update(25);
| ^^ expected type parameter, found integer
|
= note: expected type `T`
found type `{integer}`
= help: type parameters must be constrained to match other types

所以,我的问题是为什么 cache.update(25)来自 main 的方法工作函数但不是来自 increment功能?

最佳答案

因为在 main ,编译器知道它正在处理 Cache使用整数类型作为类型参数。然而,在 increment函数,可以传入 Cache任何泛型类型,因为您接受 Cache<T>作为参数。因此,如果您仍然尝试调用 updateCache<T> 上带有整数参数,这将是一个问题,因此编译器不允许这样做。以 increment 为例用 Cache<String> 调用作为一个论点,cache.update(25)工作?

如果您只想使用 Cache<i32>例如,您可以限制您的 increment函数的参数类型:

fn increment(cache: &mut Cache<i32>, v: i32)

否则在函数的通用版本中,您将不得不使用类型为 T 的值。并且不能做 cache.update(25) 之类的事情

关于generics - "Expected type parameter, found integer"从函数调用但不是从 main 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com