简体   繁体   English

为什么Rust中的const函数不能调用关联的函数?

[英]Why can't const functions in Rust make calls to associated functions?

This: 这个:

const fn pow2(exp: u32) -> u32 {
    u32::pow(exp, 2)
}

Results in a compiler error: 导致编译器错误:

error[E0015]: calls in constant functions are limited to constant functions, struct and enum constructors

Is there a way to do this? 有没有办法做到这一点?

I'd like to do: 我想做:

pub const MY_BITMASK: u32 = pow2(4);

A const function cannot call a non-const function. const函数不能调用非const函数。 This is because const functions need to be able to run during compilation, so they can't call a non-const function which can only be evaluated at runtime. 这是因为const函数需要能够在编译期间运行,因此它们不能调用只能在运行时求值的非const函数。 Since u32::pow is not a const function, you can't call it from a const function. 由于u32::pow不是const函数,因此无法从const函数调用它。

The question now becomes: Why isn't u32::pow a const function? 现在的问题变成:为什么u32::pow不是const函数? And the reason for that is a current limitation of const functions: They can only contain a subset of the language. 其原因是const函数的当前限制:它们只能包含该语言的子集。 Notably, they can't contain loops or assignments. 值得注意的是,它们不能包含循环或赋值。 Since u32::pow uses both of these , it can't be marked as const and therefore can't be called from const functions. 由于u32::pow使用了这两种方法 ,因此无法将其标记为const ,因此无法从const函数中调用它。

Note that there isn't any limitation of calling associated functions from const functions, as long as the associated function is marked const . 请注意,从关联函数调用关联函数没有任何限制,只要关联函数标记为const And u32::pow is not an associated function in any case: you can call it as eg x.pow(y) . 而且u32::pow在任何情况下都不是关联函数:您可以将其称为x.pow(y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当非const成员可以在constexpr成员函数中使用? - When non-const members can be used in constexpr member functions? 为什么我可以静态调用实例函数? - Why can I call instance functions statically? 为什么不能在PHP中从抽象类调用抽象函数? - Why can't you call abstract functions from abstract classes in PHP? 这些静态函数为什么不从另一个线程按预期方式返回? - Why don't these static functions return as expected from another thread? 为什么'extern'声明不适用于C中的静态函数? - Why declaration by 'extern' doesn't work with static functions in C? 为什么在模板类静态帮助器函数中调用全局函数会导致链接器错误,而在非静态成员函数中却不会导致链接器错误? - Why does call to global function in template class static helper function result in linker errors, but not calls in non-static member functions? 使用const getter样式函数代替静态数据成员 - Using const getter-style functions in place of static data members 为什么在 C 中使用 static 函数? - Why use static functions in C? 为什么不能将ArrayList设为静态? - Why can't I make the ArrayList static? c++:为什么我不能为类“内部”的非常量静态成员赋值? - c++ : why I can't assign a value to a non-const static member "inside" a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM