gpt4 book ai didi

rust - 如何从 `self`设置关联常量(在rust中)

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

如果我的特征定义为:

pub trait foo {
const ID: u32;
...
和一个结构定义为:
pub struct fooStruct {
pub id: u32,
pub name: vec<u8>,
...
}
当我实现 fooStruct的特征时,我想做类似的事情:
impl foo for footStruct {
const ID: u32 = self.id // self does not work here
}
我的问题是:如何通过读取实现ID的结构来设置ID const(如果可能的话)?
谢谢

最佳答案

How can i set my ID const by reading from the struct that is implementing it (if its possible at all)?


我认为这是不可能的。

Like immutable variables, constants are values that are bound to a name and are not allowed to change, but there are a few differences between constants and variables...

...constants may be set only to a constant expression, not the result of a function call or any other value that could only be computed at runtime.

self.id是在运行时计算的值, const ID: u32 = self.id 将不起作用。
此外, self仅存在于方法中。

关于rust - 如何从 `self`设置关联常量(在rust中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65065957/

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