Home >Backend Development >Golang >Instantiation interface
php editor Youzi is here to introduce to you what an instantiation interface is. In object-oriented programming, an interface is a convention that defines the methods a class should implement. Instantiating an interface refers to creating an object of a class to implement the methods defined in the interface. By instantiating the interface, we can take advantage of the polymorphic feature so that different classes can implement the same interface and rewrite the corresponding methods according to the actual situation. The use of instantiation interfaces can make our code more flexible and extensible, and improve the reusability and maintainability of the code. Let's take a closer look at the usage and precautions of the instantiated interface.
I am new to go. One thing I don't understand is why I get a compile error when I want to instantiate the interface individually, but not when I use the array form of the interface.
type Flag interface { fmt.Stringer } func TestCheckRequiredFlag(t *testing.T) { testdata := []struct { st []Flag }{ { st: []Flag{//allowed &StringFlag{Name: ""}, }, }, } st := struct { st Flag }{ st: Flag{// is not allowed &StringFlag{Name: ""}, }, } }
This compound literal allocates a new structure instance with the given value.
Braces {}
Used for literal values of slices, structures, arrays, and maps. They are not used for interface values. If you want a literal value of an interface type, you must use the ()
syntax, which calls "type conversion".
For example:
x := myinterface(&mystruct{})
x
is of type myinterface
.
To correct your code:
st := struct { st flag }{ st: flag( &stringflag{name: ""}, ), }
You can also remove the type conversion entirely, since go allows direct assignment to interface values and the conversion is implicit. More specifically, the Assignability rule says (edited for clarity):
If t is an interface type and x implements t, then a value x of type v is assignable to a variable of type t.
So, this code will also work:
st := struct { st Flag }{ st: &StringFlag{Name: ""}, }
Note that in compound literals such as slices, structs, and maps, the given values are treated as assigned to their respective indexes, fields, or keys as if they were variables, and thus can Distributive Rules Application.
The above is the detailed content of Instantiation interface. For more information, please follow other related articles on the PHP Chinese website!