這段代碼完美地作業(playground):
struct MyStruct<const B: bool> 。
impl MyStruct<false> {
pub fn bar() {
println!("false") 。
}
}
impl MyStruct<true> {
pub fn bar() {
println!("true") 。
}
}
impl MyStruct<false> {
pub fn foo() {
MyStruct::<false>::bar()
}
}
impl MyStruct<true> {
pub fn foo() {
MyStruct::<true>::bar()
}
}
fn main( ) {
MyStruct::<false>::foo()。
MyStruct::<true>::foo()。
}
其結果是:
false
真
另一方面,這段代碼會失敗(playground):
struct MyStruct<const B: bool> 。
impl MyStruct<false> {
pub fn bar() {
println!("false") 。
}
}
impl MyStruct<true> {
pub fn bar() {
println!("true") 。
}
}
impl<const B: bool> MyStruct< B> {
pub fn foo() {
MyStruct::<B>::bar()
}
}
fn main() {
MyStruct::<false>::foo()。
MyStruct::<true>::foo()。
}
結果是:
error[E0599]: no function or associated item named `bar` for struct `MyStruct<B> ` in the current scope
--> src/main.rs:16:24
|
1 | struct MyStruct<const B: bool>;
| ------------------------------- 函式或相關專案`bar`沒有找到這個
...
16 | MyStruct::<B>:bar()
| ^^^ 在`MyStruct<B>`中沒有找到函式或關聯項。
|
=注意:該函式或關聯項是為
- `MyStruct<false>`的函式或關聯項。
- `MyStruct<true>`。
我可以理解在無限值型別的情況下的這個錯誤,但為什么是布林值?
有什么方法可以克服這個問題嗎?
uj5u.com熱心網友回復:
人們必須使用特質和通用型別調節(playground):
struct MyStruct<const B: bool> 。
trait Bar {
fn bar()。
}
impl Bar for MyStruct<false> {
fn bar() {
println!("false") 。
}
}
impl Bar for MyStruct<true> {
fn bar(){
println!("true") 。
}
}
impl<const B: bool> MyStruct< B>
where?
MyStruct<B>。吧。
{
pub fn foo() {
MyStruct::<B>::bar()
}
}
fn main() {
MyStruct::<false>::foo()。
MyStruct::<true>::foo()。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318634.html
標籤:
下一篇:從基類重寫通用方法
