当前位置:网站首页>[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function

[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function

2022-07-01 19:27:00 Autumn sunset

1. Type the alias And Custom type

Custom type It's a new one type And type aliases It's still the same type But it's just an alias

// Customize new types 
type Myint int

// Type the alias 
type intAli = int

func main() {
    

	//  Print their types separately 
	var t1 Myint
	var t2 intAli
	of1 := reflect.TypeOf(t1)

	fmt.Println(of1)

	of2 := reflect.TypeOf(t2)

	fmt.Println(of2)

	fmt.Println()

}

// Output results 

main.Myint
int

2. Define function types

//  Custom function type 
type myMethod func(int, string) string

Be careful : Any satisfaction has the same formal parameter list and The return value of function Can be regarded as It is our custom function type

//  Custom function type 
type myMethod func(int, string) string

m1 := func(i1 int, s1 string) string {
    
    itoa := strconv.Itoa(i1)
    return itoa + s1
}

var m2 myMethod
	m2 = m1

3. Interface

Follow Java equally Go Interface in language It also defines the behavior specification of an object , Only define the specification, not implement , Specification details are implemented by specific objects

But with Java The difference is Go The interface in the language is non intrusive and Java Must be displayed

Go It also advocates interface oriented programming

3.1 An interface is a type

stay Go Interface in language (interface) It's a type of , An abstract type .

interface It's a group. method Set , Interfaces do things like defining a protocol ( The rules ), Don't care what kind of person they are , Only care about what the other party can do . This is a duck-type programming A manifestation of , As long as an object can call like a duck, we can call it a duck ; As long as a software can store and query data, we can call it a database ; As long as a machine has the functions of washing clothes and drying, we can call it a washing machine .

To protect your Go Language career , Remember the interface (interface) It's a type of .

3.2 Definition of interface

type  The interface name  interface{
    

     Method name one ( Parameter one , Parameter two ...)   Method return value 
     Method name two ( Parameter one , Parameter two ...)  Method return value 

}

3.3 Interface implementation

A structure Realized All methods of this interface It's the implementation of this interface One less way perhaps Inconsistent return value type Are not the implementation type of this interface

As shown in the following code :

Structure woman and man Realized say() and eat() Method This is the realization of human Interface

All we can Define a human type To accept woman and man type

//  Define an interface 
type human interface {
    
	// An interface is a collection of methods 
	say()
	eat()
}

// Define the implementation types of the two interfaces 
type woman struct {
    
	name string
	age  int
	sex  string
}
type man struct {
    
	name string
	age  int
	sex  string
}

// Realization   All in the interface   Method   That is, the interface is implemented 

func (w woman) say() {
    
	fmt.Println(" Men speak well ")
}

func (w woman) eat() {
    
	fmt.Println(" Women eat slowly ")
}

func (m man) say() {
    
	fmt.Println(" Women speak sweetly ")
}

func (m man) eat() {
    
	fmt.Println(" Men wolf down their meals ")
}

3.3.1 Value receiver and Pointer receiver The difference between

If When a method of a class implements an interface with a pointer receiver , Only The pointer of this class is considered to implement the interface

As long as the interface Any method is to correct the receiver It must be a pointer to a class It's just Interface implementation Variable

//  Define an interface 
type human interface {
    
	// An interface is a collection of methods 
	say()
	eat()
}


//  Define a structure 
type man struct {
    
	name string
	age  int
	sex  string
}


// Realization   All in the interface   Method   That is, the interface is implemented \
//  Be careful   The binding is   Pointer to structure 

func (w *woman) say() {
    
	fmt.Println(" Men speak well ")
}

func (w *woman) eat() {
    
	fmt.Println(" Women eat slowly ")
}


//  because   The interface method is   Pointer receiver   therefore   yes   The pointer of the structure implements the interface 

	var w1 human = &woman{
    
		name: " Jingxiang ",
		age:  18,
		sex:  " Woman ",
	}

3.4 Relationship between interface and type

A type can implement multiple interfaces , An interface can also be implemented by multiple types

3.5 Nesting of interfaces

//  Interface nesting   Nested two interface types   One  teacher  and   One  student  Interface 
type school interface {
    
	teacher
	student
}

type teacher interface {
    
	say()
}

type student interface {
    
	study()
}

// Define a type 
type hman struct {
    
	name string
	age  int
}

//  Use this type as the recipient of the method   Implement two interfaces respectively   It is equivalent to implementing this interface 
func (h hman) say() {
    
	fmt.Println(" The teacher gives lectures in class ")
}

func (h hman) study() {
    
	fmt.Println(" Students study in class ")
}

func main() {
    
	// Whether the interface type can be used to receive   test 
	//  Define an interface type 
	var schhum school = hman{
    
		name: " Zhang San ",
		age:  19,
	}

	schhum.say()

	//interfaceMethod()
}

4.Go Package in language package

4.1 The definition of package

A package can be simply understood as a store .go File folder . All under the folder Go The following code should be added to the first line of the code , The package to which this document belongs

matters needing attention :

  1. A file can only belong to one package
  2. The file name cannot duplicate the package name
  3. Package name is mian The package of is the entry package of the application , This package compiles to get an executable , Compilation does not include main The package will not get an executable

4.2 Package visibility

If you want to refer to an identifier in another package in one package ( Such as Variable , Constant , type , function ) when , The Identifiers must be externally visible . Be similar to Java Medium public And in the Go in Just capitalize the first letter of the identifier

In the structure The first letter of a field is lowercase For other books This field is invisible

// Visible constants 
const Sex string = " male "

//  invisible   Constant 
const age int = 19

// so   function 
func CanSee() {
	fmt.Println(" You see me ")
}

//  Invisible function 
func notCanSee() {
	fmt.Println(" Carrying a suitcase ")
}

// Visible structure 
type Human struct {
	//  Serializable 
	Name string
	//  Not serializable   invisible 
	age string
}

//  Invisible structure 
type student struct {
	date string
}

4.3 Package import

If you need to use identifiers under other packages This package needs to be imported The grammar is as follows

import " The path of the package "

matters needing attention :

  1. import The import statement is usually placed below the declaration statement at the beginning of the file
  2. The imported package name needs to be In double quotation marks
  3. The package name comes from $GOPATH/src/ And then we start to calculate , Use / Path separation .
  4. Go Circular guide packages are forbidden in language

4.4 Custom package name

While importing the package We can also set aliases for packages . Setting an alias is usually used when the package name is too long or the imported package name is re entered

import  Alias  " The path of the package "

4.5 Anonymous import package

If you only need to import the package without using the data in the package Anonymous packages can be used Equate to When customizing the package name There's a A hidden name

import _ " The path of the package "

5. Initialization function

5.1 init Function considerations

Go Language When executing the import package statement Will automatically execute the imported package init function

matters needing attention

  1. init The function has no arguments and no return value
  2. Imported package init The function will be called automatically
  3. One .go Files can have more than one init function
  4. main Of the program entry file init The function will also execute It's just under other packages init After the functions are executed ,main Before method execution

5.2 init Function execution time

img

5.3 init function Execution order

When Guide pack There is one. Hierarchy nesting When Of the last imported package init The function will be executed first

img

end Exercises

1. Write a calc Package to realize four functions of addition, subtraction, multiplication and division , stay snow This package imports and uses four functions of addition, subtraction, multiplication and division to realize mathematical operation .

package calc

// Add 
func Sum(x int, y int) int {
	return x + y
}

// Subtraction 
func Sub(x int, y int) int {
	return x - y
}

//  Multiplication 
func Mult(x int, y int) int {
	return x * y
}

// division 
func Div(x int, y int) int {
	return x / y
}
package main

// Import calc package 

import (
	// Pack aliases 
	"fmt"
	cl "go_todo/calc"
)

func main() {
	//  add 
	sum := cl.Sum(1, 9)
	fmt.Printf(" The result of adding two numbers is  %d \n", sum)

	// subtracting 
	sub := cl.Sub(100, 99)
	fmt.Printf(" The result of subtracting two numbers is  %d \n", sub)

	// Do multiplication 
	x, y := 5, 20
	mult := cl.Mult(x, y)
	fmt.Printf("%d  ride  %d = %d \n", x, y, mult)

	x, y = 100, 4
	div := cl.Div(x, y)
	fmt.Printf("%d  except  %d = %d \n", x, y, div)
}
原网站

版权声明
本文为[Autumn sunset]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011721583955.html