当前位置:网站首页>Golang quick start (3)
Golang quick start (3)
2022-06-23 10:22:00 【Dog barking】
Catalog
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

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]]

边栏推荐
猜你喜欢

漫画 | Code Review快把我逼疯了!

Golang 快速上手 (1)

Lying trough, the most amazing paper artifact!

Nuxt.js spa与ssr的区别

太无奈!微软停售 AI 情绪识别等技术,直言:“法律跟不上 AI 的发展”

文献综述怎么写 ,一直没头绪写不出来怎么办?

Nuxt. Differences between JS spa and SSR

sql编写问题,求出当月和上月的环比值

Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file

Go language JSON processing
随机推荐
5次登陆失败,限制登录实践
2021-05-11 static keyword
Successful experience of postgraduate entrance examination in materials and Chemical Engineering (metal) of Beijing University of Aeronautics and Astronautics in 2023
mysql innodb 的 redo log buffer 中未 commit 的事务持久化到 redo log 后,万一事务 rollback 了怎么办?redo log 怎么处理这个事务操作?
Numerical calculation method
数学分析_笔记_第2章:实数与复数
Bugs encountered in Oracle
Bi SQL drop & alter
用贪吃蛇小游戏表白(附源码)
实现领域驱动设计 - 使用ABP框架 - 通用准则
Is IPv6 faster than IPv4?
几款实用软件分享
Bioinformatics | effective drug target correlation prediction based on interacting neural network
Unity技术手册 - 生命周期LifetimebyEmitterSpeed-周期内颜色ColorOverLifetime-速度颜色ColorBySpeed
在OpenCloudOS使用snap安装.NET 6
MySQL optimistic lock and pessimistic lock
Find minimum in rotated sorted array
2021-05-07封装 继承 super this
SQL writing problem to calculate the ring ratio of the current month and the previous month
sql根据比较日期新建字段