You tried to use a type which doesn't implement some trait in a place which expected that trait.
何らかの trait を実装していない型を、その trait を期待していた場所で使おうとしました
Erroneous code example:
// here we declare the Foo trait with a bar method
// ここで Foo trait を bar メソッドと共に宣言しています
trait Foo {
fn bar(&self);
}
// we now declare a function which takes an object implementing the Foo trait
// Foo trait を実装したオブジェクトを受け取る関数を宣言します
fn some_func<T: Foo>(foo: T) {
foo.bar();
}
fn main() {
// we now call the method with the i32 type, which doesn't implement
// the Foo trait
// ここでは、Foo trait を実装してない、i32型でメソッドを呼び出しています
some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
// ①????
}
In order to fix this error, verify that the type you're using does implement the trait. Example:
このエラーを修正するには、使用している型がその trait を実装していることを確認してください。 例を挙げてみます。
trait Foo {
fn bar(&self);
}
fn some_func<T: Foo>(foo: T) {
foo.bar(); // we can now use this method since i32 implements the
// Foo trait
// i32 は Foo trait を実装しているので、このメソッドを使うことができます。
}
// we implement the trait on the i32 type
// i32型に trait を実装します
impl Foo for i32 {
fn bar(&self) {}
}
fn main() {
some_func(5i32); // ok!
}
Or in a generic context, an erroneous code example would look like:
あるいは、一般的な事情では、誤ったコードの例は次のようになります:
fn some_func<T>(foo: T) {
println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
// implemented for the type `T`
// trait `core::fmt::Debug` は型 `T` に実装されていません。
}
fn main() {
// We now call the method with the i32 type,
// which *does* implement the Debug trait.
// ここでは、i32 型のメソッドを呼び出しますが、これは Debug trait を実装しています。
some_func(5i32);
}
Note that the error here is in the definition of the generic function: Although
we only call it with a parameter that does implement Debug
, the compiler
still rejects the function: It must work with all possible input types. In
order to make this example compile, we need to restrict the generic type we're
accepting:
ここでのエラーは汎用関数の定義にあることに注意してください。この関数を Debug
を実装したパラメータで
呼び出しただけなのに、コンパイラはこの関数を拒否します。それはすべての可能な入力タイプで動作しなければ
なりません。この例をコンパイルするためには、受け入れる汎用型を制限する必要があります。
use std::fmt;
// Restrict the input type to types that implement Debug.
// 入力タイプをDebugを実装したタイプに制限します。
fn some_func<T: fmt::Debug>(foo: T) {
println!("{:?}", foo);
}
fn main() {
// Calling the method is still fine, as i32 implements Debug.
// i32はDebugを実装しているので、メソッドを呼び出しても問題ありません。
some_func(5i32);
// This would fail to compile now:
// これはコンパイルに失敗します。
// struct WithoutDebug;
// some_func(WithoutDebug);
}
Rust only looks at the signature of the called function, as such it must already specify all requirements that will be used for every type parameter.
Rust は呼び出された関数のシグネチャだけを見るので、すべての型パラメータに使用されるすべての要件を すでに指定している必要があります。