How to declare an interface using the go interface keyword?
In Go language, you can use the type keyword to declare an interface. An interface is an abstract type that defines a set of methods without any specific implementation. The syntax for declaring an interface is as follows:
type 接口名 interface {
方法名1(参数列表) 返回值列表
方法名2(参数列表) 返回值列表
// ...
}
For example, let’s say we want to define an Animal interface with a Speak method.
type Animal interface {
Speak() string
}
This interface represents animals that can make sounds. Any type that implements the Speak method can be considered as an implementation type of the Animal interface. The methods of the interface do not need to be explicitly implemented, as long as the method name, parameter list, and return value list match the interface definition.
Here is an example of the Cat type implementing the Animal interface:
type Cat struct{}
func (c Cat) Speak() string {
return "Meow!"
}
In this example, the Cat type implements the Speak method of the Animal interface, and returns the string “Meow!”.
You can use the interface in the following ways:
func main() {
var animal Animal
animal = Cat{}
fmt.Println(animal.Speak()) // 输出:"Meow!"
}
In the main function, we declared a variable named animal of type Animal, and then assigned an instance of type Cat to it. Next, we called the animal.Speak() method, which outputted “Meow!”.