当前位置:网站首页>[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 :
- A file can only belong to one package
- The file name cannot duplicate the package name
- 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 :
- import The import statement is usually placed below the declaration statement at the beginning of the file
- The imported package name needs to be In double quotation marks
- The package name comes from $GOPATH/src/ And then we start to calculate , Use / Path separation .
- 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
- init The function has no arguments and no return value
- Imported package init The function will be called automatically
- One .go Files can have more than one init function
- 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

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

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)
}
边栏推荐
- MySQL common graphics management tools | dark horse programmers
- SuperVariMag 超导磁体系统 — SVM 系列
- 小红书上的爱情买卖
- The former 4A executives engaged in agent operation and won an IPO
- Solution of intelligent supply chain management platform in aquatic industry: support the digitalization of enterprise supply chain and improve enterprise management efficiency
- Lumiprobe phosphide hexaethylene phosphide specification
- Huawei game failed to initialize init with error code 907135000
- Solidity - 合约结构 - 错误(error)- ^0.8.4版本新增
- 中英说明书丨人可溶性晚期糖基化终末产物受体(sRAGE)Elisa试剂盒
- kubernetes命令入门(namespaces,pods)
猜你喜欢
![[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched](/img/5c/b0030fd5fbc07eb94013f2699c2a04.png)
[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched

Solidity - 算术运算的截断模式(unchecked)与检查模式(checked)- 0.8.0新特性

Cdga | if you are engaged in the communication industry, you should get a data management certificate

Prices of Apple products rose across the board in Japan, with iphone13 up 19%

Games202 operation 0 - environment building process & solving problems encountered

Solidity - contract structure - error - ^0.8.4 NEW

The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise

XML syntax, constraints

机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效

M91 fast hall measuring instrument - better measurement in a shorter time
随机推荐
Games202 operation 0 - environment building process & solving problems encountered
The difference between indexof and includes
[quick application] win7 system cannot run and debug projects using Huawei ide
indexof和includes的区别
Yyds dry inventory ravendb start client API (III)
English grammar_ Adjective / adverb Level 3 - precautions
机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
[live broadcast appointment] database obcp certification comprehensive upgrade open class
Solution of intelligent supply chain management platform in aquatic industry: support the digitalization of enterprise supply chain and improve enterprise management efficiency
MySQL common graphics management tools | dark horse programmers
小红书上的爱情买卖
【英语语法】Unit1 冠词、名词、代词和数词
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
使用环信提供的uni-app Demo,快速实现一对一单聊
学习笔记【gumbel softmax】
Lake Shore - crx-em-hf low temperature probe station
前4A高管搞代运营,拿下一个IPO
Today, with the popularity of micro services, how does service mesh exist?
Junit单元测试框架详解