function
- Definition and use of functions
Parameters, return values, multiple return values
- variable length variable
func Add(a int, args ...int) (result int)
Variable-length parameters can only be placed at the end, and can be used as a slice when used
- pass-by-value and reference types
The reference types in the go language are: slice, dictionary (map), interface, function type and channel (chan)
- Anonymous functions and closures
- defer usage
- panic and recover
The code behind panic will not be executed, and recovery is usually written in defer.
When panic occurs, the defer before it will be executed, and the program will exit after execution. The defer after panic will not be executed.
method
In contrast to normal functions, the default first parameter of a method is the type itself. When the method is a method of a pointer to a type, it can be called using the type or the type pointer. But if the method is a method of a type, it can only be called with the type.
type Person struct { name string age int } func (p *Person) addAge(num int) { fmt.Println(p.age) p.age += num } transfer: var p Person = Person{} p.addAge(10) fmt.Println(p.age)Since the first parameter of the method is the type itself, it can also be called like this:
(*Person).addAge(&p,20)
interface
Interface definition and basic operations
Embedding an interface
Type assertion
Empty interface and type switch
Embedding an interface
Type assertion
Empty interface and type switch
package main import ( "fmt" ) type Usb interface { Aprint(str string) } type Usb1 struct { name string } func (c Usb1) Aprint(str string) { fmt.Println(c.name) } func main() { var d Usb = Usb1{"usb1"} //--- if u1, ok := d.(Usb1); ok { fmt.Println(u1.name) } //---- switch v := d.(type) { case Usb1: fmt.Println(v.name) default: fmt.Println("unkonw type") } }
Interface Conversion
Interface Usage Precautions