当前位置:网站首页>Golang quick start (3)

Golang quick start (3)

2022-06-23 10:22:00 Dog barking


Structure

Golang There is no direct object-oriented concept , But you can use Go Syntax to implement some features of object-oriented programming , for example : Inherit 、 polymorphic 、 Other characteristics .


Define a structure

type Animal struct {
    
	Name string
	Age  int
}

Initialize structure

Default initialization

	var dog Animal // Define a structure 

Use key value pairs to initialize

animal := Animal{
    
		Name: "animal",
		Age:  19,
	}

List initialization

All fields of the structure must be initialized .
The initial values must be filled in the same order as the fields are declared in the structure .
This method cannot be mixed with the key initialization method .

	cat := Animal{
    
		"cat",
		12,
	}

Partial initialization

	cat := Animal{
    
		Name: "cat",
	}


Pointer to structure

new Keyword to create a structure pointer

	pa := new(Animal)
	fmt.Printf("pa: %T\n", pa) //pa: *main.Animal

Access structure members

Both the pointer and the object can access the members of the structure object through commas , If the pointer accesses a member through a comma, the compiler will dereference by default ,(*pa),name Equivalent to pa.name

	pa := new(Animal)
	pa.Name = "fish"
	pa.Age = 3

	(*pa).Name = "dog"
	(*pa).Age = 4
	fmt.Printf("pa: %v\n", *pa) //pa: {dog 4}

Access to the structure

Structure names are capitalized , Then it can be defined in other packages Person object , Lowercase is not accessible .

also , If the attribute of the structure is capitalized, its access permission is public Of , If lowercase , Then for private

type Person struct {
    
	Name string
	Age  int
}

func main() {
    
	p1 := Person{
    
		Name: "marry",
		Age:  30,
	}

	fmt.Printf("p1.Name: %v\n", p1.Name)
	fmt.Printf("p1.Age: %v\n", p1.Age)
}

Compiler error

type Person struct {
    
	name string
	age  int
}

func main() {
    
	p1 := Person{
    
		name: "marry",
		age:  30,
	}
	//p1.Name undefined (type Person has no field or method Name, but does have name)
	fmt.Printf("p1.Name: %v\n", p1.Name)
	fmt.Printf("p1.Age: %v\n", p1.Age)
}

Methods can only be accessed in other packages if they are capitalized


type Person struct {
    
	name string
	age  int
}

func (p Person) Run() {
    
	fmt.Println("Person Run")
}

func main() {
    
	p1 := Person{
    
		name: "marry",
		age:  30,
	}
}

Object method

Golang There is no direct provision of object-oriented features , There is no concept of class objects . however , You can use structures to simulate these properties .


Define structure method

Golang The method in , It's a special function , Defined in struct above ( And struct relation 、 binding ), go by the name of struct The recipient of (receiver).

type Animal struct {
    
	Name string
	Age  int
}

func (a Animal) Eat() {
    
	fmt.Println("Animal Eat")
}

func (a Animal) Sleep() {
    
	fmt.Println("Animal Sleep")
}

func main() {
    

	a := Animal{
    
		Name: "dog",
		Age:  10,
	}

	a.Eat()
	a.Sleep()
}

Receiver type

// Pass a pointer to change its value 
func (per *Animal) Set1(age_ int, name_ string) {
    
	per.age = age_
	per.name = name_
}

// Value passed   Internal modifications do not affect external 
func (per Animal) Set2() (int, string) {
    
	per.age = age_
	per.name = name_
}

Method points for attention

  • Methodical receiver type It could be other types , Such as :type Defined type alias 、slice、 map、 channel、 func Type, etc

  • struct The method combined with it is equivalent to the class in object-oriented . It's just struct It can be separated from its method ,, It doesn't have to belong to the same file , But it must belong to the same package .

  • Methods have two types of reception : (T Type) and (T *Type) , (T Type) It's worth passing on ,(T *Type) Pass pointer , Internal modifications affect the arguments .

  • The method is the function ,,Go There is no method overload in (overload) That's what I'm saying , That is, all method names in the same type must be unique .

  • If receiver It's a pointer type , Will automatically dereference .

  • Methods and type It's separate. , Means the behavior of the instance (behavior) And data storage (field) It's separate. , But they go through receiver Establish relational relationships .



Interface

go Language interface , Is a new type definition , It defines all the common methods together , Any other type that implements these methods implements this interface .
The syntax format and method are very similar .

Define an interface

type Displayer interface {
    
	DisplayAudio(string)
	Displayvideo(string)
}

Implementation interface

type Displayer interface {
    
	DisplayAudio()
	DisplayVideo()
}
 
type MP4 struct {
    
}

func (mp4 MP4) DisplayAudio() {
    
	fmt.Println("DisplayAudio")
}

func (mp4 MP4) DisplayVideo() {
    
	fmt.Println("DisplayVideo")
}

func main() {
    

	var player Displayer = MP4{
    }

	player.DisplayAudio()
	player.DisplayVideo()
}

it is to be noted that , To implement an interface, you must implement all the methods in the interface , Otherwise, the structure cannot be assigned to the interface type variable


Value type receiver Pointer types receiver

The same as method parameters , You must pass a pointer to modify its value internally ..



Interface and struct

One structure can implement multiple interfaces
Multiple structures implement the same interface ( Realizing polymorphism )


One structure implements multiple interfaces

type Displayer interface {
    
	DisplayAudio()
	DisplayVideo()
}

type PlayGamer interface {
    
	PlayGame()
}

type MP4 struct {
    
	Volume int
}

func (mp4 MP4) DisplayAudio() {
    
	fmt.Println("DisplayAudio")
}

func (mp4 MP4) DisplayVideo() {
    
	fmt.Println("DisplayVideo")
}

func (mp4 MP4) PlayGame() {
    
	fmt.Println("PlayGame")
}

func main() {
    

	var player1 Displayer = MP4{
    
		Volume: 10,
	}
	var player2 PlayGamer = MP4{
    
		Volume: 10,
	}

	player1.DisplayAudio()
	player1.DisplayVideo()

	player2.PlayGame()
}

Realizing polymorphism

Multiple structures implement the same interface ( polymorphic )

package main

import "fmt"

type Per interface {
    
	eat()
	sleep()
}

type Dog struct {
    
}

type Cat struct {
    
}

func (d Dog) eat() {
    
	fmt.Println("Dog eat")
}

func (d Dog) sleep() {
    
	fmt.Println("Dog eat")
}

func (d Cat) eat() {
    
	fmt.Println("Cat eat")
}

func (d Cat) sleep() {
    
	fmt.Println("Cat eat")
}


type Person struct {
    
}

func (p Person) care(per Per) {
    
	per.eat()
	per.sleep()
}

// In fact, it is the use of polymorphism 
//OCP  Open expansion   Close changes 
func main() {
    

	dog := Dog{
    }
	cat := Cat{
    }

	person := Person{
    }
	person.care(dog)
	person.care(cat)
}

Simply implement a polymorphic case , Pass on Dog Object calls Dog Class method , Pass on Cat Object call Cat Class method .



Inherit

Define a parent class

type Animal struct {
    
	Name string
	Age  int
}

func (a Animal) Sleep() {
    
	fmt.Println("Animal Sleep")
}

func (a Animal) Eat() {
    
	fmt.Println("Animal Eat")
}

Subclasses can redefine the methods of the parent class

type Dog struct {
    
	Animal
}
func (d Dog) Eat() {
    
	fmt.Println("Dog Eat")
}

func main() {
    
		d1 := Dog{
    
		Animal: Animal{
    
			Name: "Dog",
			Age:  3,
		},
	}
	d1.Eat() //Dog Eat
}


Golang Constructors

golang There is no concept of constructors , But you can use functions to simulate the functions of constructors .

type Student struct {
    
	Name string
	Age  int
}

func NewStudent(name string, age int) (*Student, error) {
    

	if age > 99 || age < 0 {
    
		return nil, fmt.Errorf("age input error")
	}

	return &Student{
    Name: name, Age: age}, nil
}


Golang package

 Insert picture description here

Packages can distinguish between command spaces ( There cannot be two files with the same name in a folder ), It can also better manage the project .go Create a package in , Usually create a folder , In this folder go In file , Use package Keyword declares the package name , Usually , The folder name is the same as the package name . And there is only one package under the same file

Attention of the bag :

There can only be one in a folder package

  • import The back is actually GOPATH Starting relative directory path , Including the last paragraph . But because there can only be one in a directory package, therefore import A path is equal to import The package under this path .

We need to pay attention to , This means “ Direct contains ” Of go file . If there are subdirectories , Then the parent directory of the subdirectory is completely two packages .
For example, a calculator is implemented package, named calc, be located calc Under the table of contents . But I want to give others an example , So in calc You can build a example subdirectories (calc/example/) , There is a in this subdirectory example.go (calc/example/example.go) . here ,example.go It can be main package , There can also be a main function .

  • One package The files of cannot be in more than one folder

If multiple folders have duplicate names package, They have nothing to do with each other package.
If one go Files need to use the same name in different directories at the same time package, Need to be in import When these directories, specify one for each directory package Another name for .|


How to import packages

Anonymous import

Once the package is imported, its internal functions must be used , If the compiler is not used, an error is reported , But if there is a need , Need to call test_lib Of init function , Without calling test_lib The function in can be used _ Anonymous import package .

import (
	"fmt"
	_ "test_lib"
)

Rename the package :

If the package name is too long , You can rename it using .

import (
	"fmt"
	my_lib "test_lib"
)

func main() {
    
	my_lib.API()
}

Expand package :

test_lib Add a comma before the package name , So called test_lib Functions in can be without package name , Just like the function definition in the current package .

import (
	"fmt"
	. "test_lib"
)
func main() {
    
	API() // test_lib.API()  Call directly 
}

It is not recommended to use , If both packages use commas to expand the package , If a function with the same name exists in two packages, it cannot be distinguished .


Package management tools module

go modules yes golang 1.11 New features , It is used to manage the dependencies of packages in the module .

Commonly used instructions

Initialization module

go mod init < Project module name >

Dependency handling , according to go.mod file

go mod tidy

Copy the dependency package to vendor Catalog .
If you can't access the Internet scientifically , You can use this command , Subsequent use go build -mod=vendor compile

go mod vendor

Show dependencies

go list -m all

Show detailed dependencies

go list -m -json all

Download dependency ([[email protected]] It's not necessary to write )

go mod download [[email protected]]

 Insert picture description here


原网站

版权声明
本文为[Dog barking]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230955467477.html