docs

#E0069: 未滿足 trait 約束

某個型別沒有實作泛型參數、關聯型別或槽位所要求的 trait。為該型別實作這個 trait,或改用具備它的型別。重複字面值 [v; N] 會把 v 複製(clone)到每個元素,所以 v 必須是 Clone,而且不能是只有一個擁有者的資源;這種陣列請用 array::from_fn::<T, N>(|_| ..) 逐一建立元素。

nabi
fn keep<T: Clone>(x: T) -> T { x }
struct P { x: i32; }

println(f"{keep(P { x: 1 }).x}");
error[E0069]: type `P` does not satisfy trait bound `Clone` required by `keep`
  --> main.nabi:4:12
   |
 4 | println(f"{keep(P { x: 1 }).x}");
   |            ^^^^^^^^^^^^^^^^

為型別實作這個 trait,這裡用衍生的方式:

nabi
fn keep<T: Clone>(x: T) -> T { x }
#[derive(Clone)]
struct P { x: i32; }

println(f"{keep(P { x: 1 }).x}");
1

重複字面值 [v; N] 會用 clone() 讓每個元素擁有一份自己的 v,所以含有集合的元素型別也必須是 Clone:

nabi
struct Bag { xs: List<i32>; }

let bags = [Bag { xs: [] }; 3];
error[E0069]: `[v; N]` copies `v` into each element with `clone()`, but `Bag` is not `Clone`
  --> main.nabi:3:12
   |
 3 | let bags = [Bag { xs: [] }; 3];
   |            ^^^^^^^^^^^^^^^^^^^
   |
   = help: build each element on its own: `array::from_fn::<Bag, 3>(|_| ..)`

為型別衍生 Clone,或逐一建立每個元素:

nabi
struct Bag { xs: List<i32>; }

let bags = array::from_fn::<Bag, 3>(|_| Bag { xs: [] });
bags[0].xs.push(1);
println(f"{bags.len()} {bags[0].xs:?} {bags[1].xs:?}");
3 [1] []

相關錯誤碼:E0054 無法套用的運算子、E0077 未實作父 trait、E0088 無效的格式

發現錯誤? 在 GitHub 上編輯此頁 最後更新: