An overview of the

The three consecutive sections are as follows:

  • The first section covers basic syntax and data structures
  • Section 2 discusses methods and interfaces
  • The third section briefly introduces the concurrency primitives of Go.

methods

Go has no classes. However, you can define methods for struct types. Methods are a class of functions that take special receiver parameters. The method receiver is in its own argument list, between the func keyword and the method name

Func (v Vertex) Abs() float64 {return math.sqrt (v.X*v.X + v.Y*v.Y)} v := Println(v.abs ()) A method is just a function with a receiver argument. Func Abs(v Vertex) float64 {return math.sqrt (v.X*v.X + v.Y*v.Y)}Copy the code

The receiver’s type definition and method declaration must be in the same package; Methods cannot be declared for built-in types. You can also declare methods for non-struct types.

type MyFloat float64
Copy the code

Select the value or pointer as the receiver

Pointer receivers are used for the following reasons:

  1. Method can modify the value pointed to by its receiver.
  2. This avoids copying the value each time the method is called. This is more efficient when the value is of type large structure.

Interfaces and implicit implementations

In contrast to Java and Implements, which require declared interfaces, Go uses implicit implementation. The declaration and implementation of an interface do not need to be referenced. In this way, the implementation of the interface can appear in any package without having to reference the definition file of the interface in advance.

The interface values

PS: In fact, a Java-like interface reference can be passed as a parameter, through which to achieve object-oriented polymorphism. Interface values hold a specific value for a specific underlying type. When an interface value calls a method, it executes a method of the same name of its underlying type. Interfaces are also values. They can be passed like any other value, and the interface value can be used as a parameter or return value to a function

Interface value whose underlying value is nil

Even if the value the interface points to is nil, the method will still be called by the nil receiver. When an interface refers to nil, the interface itself is not nil, but you can think of methods as functions, and we can still judge nil postprocessing in this method

type Person struct { name string } type IWalk interface { walk() } func (p *Person) walk() { if p == nil { fmt.Println("  <nil> ") return } fmt.Println(p.name," walking ") }Copy the code

When the value (object) to which the interface points is nil

When an interface points to a value (object) that is nil, neither the value nor the concrete type is saved. Calling a method produces a runtime error because you don’t know which (method/function) to call.

Empty interfaces like interface{}. An interface that specifies 0 methods is called a null interface. A null interface can hold any type of value. (Because each type implements at least zero methods.) Empty interfaces are used to handle values of unknown types.

Type assertion A type assertion provides access to the underlying concrete value of an interface value.

 t := i.(T)
Copy the code

To determine whether an interface value holds a particular type, a type assertion returns two values: its underlying value and a Boolean value that reports whether the assertion was successful.

t, ok := i.(T)

var i interface{} = "hello"
s, ok := i.(string)
fmt.Println(s, ok)
Copy the code

Type selection

Type selection is a structure that selects branches sequentially from several type assertions.

i.(type)
Copy the code

This way intelligence is used in switch.

Type selection is similar to a normal Switch statement, except that cases in type selection are types (not values), and they are compared against the types of values stored for a given interface value.

Switch v := I.(type) {case T: // V is of the type T case S: // V is of the type S Default: // No match, v is of the same type as I}Copy the code

Stringer

Stringer, defined in the FMT package, is one of the most common interfaces.

type Stringer interface {
    String() string
}
Copy the code

String () returns a string. Stringer is a type that can describe itself as a string. FMT packages (and many more) print values through this interface.

type Person struct {
  Name string
  Age  int
}

func (p Person) String() string {
  return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

z := Person{"Zaphod Beeblebrox", 9001}
fmt.Println(a, z)
Copy the code

error

The Go program uses an error value to indicate error status. The error type is a built-in interface:

type error interface {
    Error() string
}
Copy the code

When FMT encounters an error object while printing a value, it calls the error method

type Obj struct {
name string
}

func (o *Obj) Error() string {
return fmt.Sprintf(" obj(%v's Error)",o.name)
}

func main() {
var error = &Obj{"zhang3"}
fmt.Println(error)

}
Copy the code

Normally the function returns an error, and the calling code should determine if the error is nil to handle the error.

i, err := strconv.Atoi("42") if err ! = nil { fmt.Printf("couldn't convert number: %v\n", err) return } fmt.Println("Converted integer:", i)Copy the code

Error is nil, success; Non-nil error means failure.

Reader

The IO package specifies the IO.Reader interface, which represents reading from the data stream.

The IO.Reader interface has a Read method:

 func (T) Read(b []byte) (n int, err error)
Copy the code

Read fills the given byte slice with data and returns the number of bytes filled and an error value. It returns an IO.eof error when it encounters the end of the data stream. The Go standard library contains many implementations of this interface, including files, network connections, compression, and encryption.

Example:

var r io.Reader r = strings.NewReader("Hello, Reader!" ) var b []byte b = make([]byte,8) for{ n,err := r.Read(b) fmt.Printf(" n=%v,err=%v b=%v \n",n,err,b) result := b[:n] fmt.Printf("result = %q \n",result) if err == io.EOF { break } }Copy the code

image

The image package defines the image interface:

package image

type Image interface {
    ColorModel() color.Model
    Bounds() Rectangle
    At(x, y int) color.Color
}
Copy the code

It means: 1. Color mode 2. Range size 3

Note: the Rectangle returned by the Bounds method is actually an image.Rectangle declared in the image package.

The image.rect () method builds a Rect

Example:

m := image.NewRGBA( image.Rect( 0, 0, 100, 100) )
fmt.Println(m.Bounds())
fmt.Println(m.At(0, 0).RGBA())
Copy the code

Learn more

docscn.studygolang.com/doc/

go-zh.org/#

tour.go-zh.org/list

END