Go语言基础:Pointer指针、Structs结构体、Methods方法详细教程案例

目录标题

  • 一、Pointer
    • [1. Declaring pointers](#1. Declaring pointers)
    • [2. Zero value of a pointer](#2. Zero value of a pointer)
    • [3. Creating pointers using the new function](#3. Creating pointers using the new function)
    • [4. Dereferencing a pointer](#4. Dereferencing a pointer)
    • [5. Passing pointer to a function](#5. Passing pointer to a function)
    • [6. Returning pointer from a function](#6. Returning pointer from a function)
    • [7. Do not pass a pointer to an array as an argument to a function. Use slice instead.](#7. Do not pass a pointer to an array as an argument to a function. Use slice instead.)
    • [8. Go does not support pointer arithmetic](#8. Go does not support pointer arithmetic)
  • 二、Structs
    • [1. Creating named structs](#1. Creating named structs)
    • [2. Creating anonymous structs](#2. Creating anonymous structs)
    • [3. Accessing individual fields of a struct](#3. Accessing individual fields of a struct)
    • [4. Zero value of a struct](#4. Zero value of a struct)
    • [5. Pointers to a struct](#5. Pointers to a struct)
    • [6. Anonymous fields](#6. Anonymous fields)
    • [7. Nested structs](#7. Nested structs)
    • [8. Promoted fields](#8. Promoted fields)
    • [9. Structs Equality](#9. Structs Equality)
  • 三、Methods
    • [1. Sample Method](#1. Sample Method)
    • [2. Pointer Receivers VS Value Receivers](#2. Pointer Receivers VS Value Receivers)
    • [3. Methods of anonymous struct fields](#3. Methods of anonymous struct fields)
    • [4. Value receivers in methods VS Value arguments in functions](#4. Value receivers in methods VS Value arguments in functions)
    • [5. Pointer receivers in methods VS Pointer arguments in functions](#5. Pointer receivers in methods VS Pointer arguments in functions)
    • [6. Methods with non-struct receivers](#6. Methods with non-struct receivers)

一、Pointer

1. Declaring pointers

go 复制代码
	func main() {
		b := 255
		var a *int = &b
		fmt.Printf("Type of is %T\n", a)   // 获取值的类型
		fmt.Println("address of b is ", a) // 内存地址
		fmt.Println(b, *a)                 // 两种方法指向值
	}
	
	// Type of is *int
	// address of b is  0xc0000180c8
	// 255 255

2. Zero value of a pointer

go 复制代码
	a := 25
	var b *int
	if b == nil {
		fmt.Println("b is", b)
		b = &a	// 指向a的内存地址
		fmt.Println("b after initialization is", b)
	}

	// b is <nil>
	// b after initialization is 0xc0000180c8

3. Creating pointers using the new function

go 复制代码
	size := new(int)
	fmt.Printf("Size value is %d, type is %T, address is %v\n", *size, size, size)
	*size = 85
	fmt.Println("New size value is", *size)
	
	// Size value is 0, type is *int, address is 0xc0000a6058
	// New size value is 85

4. Dereferencing a pointer

go 复制代码
	b := 255
	a := &b
	fmt.Println("address of b is", a)
	fmt.Println("value of b is", *a)
	*a++
	fmt.Println("new values is", b)

	//address of b is 0xc0000180c8
	//value of b is 255
	//new values is 256

5. Passing pointer to a function

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	func change(val *int) {  
	    *val = 55
	}
	func main() {  
	    a := 58
	    fmt.Println("value of a before function call is",a)
	    b := &a
	    change(b)
	    fmt.Println("value of a after function call is", a)
	}
	
	// value of a before function call is 58  
	// value of a after function call is 55  

6. Returning pointer from a function

go 复制代码
	func helloWorld() *int {
		i := 5
		return &i
	}
	
	func main{
	    d := helloWorld()
	    fmt.Println("value of d", d)
	}
	
	// value of d 0xc0000180c8

7. Do not pass a pointer to an array as an argument to a function. Use slice instead.

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	func modify(arr *[3]int) {  
	    (*arr)[0] = 90
	}
	
	func main() {  
	    a := [3]int{89, 90, 91}
	    modify(&a)
	    fmt.Println(a)
	}
	
	// slice func	
	
	func modifys(sls []int) {
		sls[0] = 90
	}
	
	a := [3]int{89, 90, 91}
	modifys(a[:])
	fmt.Println(a)

8. Go does not support pointer arithmetic

go 复制代码
	b := [...]int{109, 110, 111}
	p := &b
	p++ // invalid operation: p++ (non-numeric type *[3]int)


	// Go不支持指针算术,而其他语言如C和c++中存在指针算术

二、Structs

1. Creating named structs

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Employee struct {  
	    firstName string
	    lastName  string
	    age       int
	    salary    int
	}
	
	func main() {
	
	    //creating struct specifying field names
	    emp1 := Employee{
	        firstName: "Sam",
	        age:       25,
	        salary:    500,
	        lastName:  "Anderson",
	    }
	
	    //creating struct without specifying field names
	    emp2 := Employee{"Thomas", "Paul", 29, 800}
	
	    fmt.Println("Employee 1", emp1)
	    fmt.Println("Employee 2", emp2)
	}

2. Creating anonymous structs

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	func main() {  
	    emp3 := struct {
	        firstName string
	        lastName  string
	        age       int
	        salary    int
	    }{
	        firstName: "Andreah",
	        lastName:  "Nikola",
	        age:       31,
	        salary:    5000,
	    }
	
	    fmt.Println("Employee 3", emp3)
	}

3. Accessing individual fields of a struct

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Employee struct {  
	    firstName string
	    lastName  string
	    age       int
	    salary    int
	}
	
	func main() {  
	    emp6 := Employee{
	        firstName: "Sam",
	        lastName:  "Anderson",
	        age:       55,
	        salary:    6000,
	    }
	    fmt.Println("First Name:", emp6.firstName)
	    fmt.Println("Last Name:", emp6.lastName)
	    fmt.Println("Age:", emp6.age)
	    fmt.Printf("Salary: $%d\n", emp6.salary)
	    emp6.salary = 6500
	    fmt.Printf("New Salary: $%d", emp6.salary)
	}
	
	// First Name: Sam  
	// Last Name: Anderson  
	// Age: 55  
	// Salary: $6000  
	// New Salary: $6500 

4. Zero value of a struct

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Employee struct {  
	    firstName string
	    lastName  string
	    age       int
	    salary    int
	}
	
	func main() {  
	    emp5 := Employee{
	        firstName: "John",
	        lastName:  "Paul",
	    }
	    fmt.Println("First Name:", emp5.firstName)
	    fmt.Println("Last Name:", emp5.lastName)
	    fmt.Println("Age:", emp5.age)
	    fmt.Println("Salary:", emp5.salary)
	}
	
	// First Name: John  
	// Last Name: Paul  
	// Age: 0  
	// Salary: 0  

5. Pointers to a struct

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Employee struct {  
	    firstName string
	    lastName  string
	    age       int
	    salary    int
	}
	
	func main() {  
	    emp8 := &Employee{
	        firstName: "Sam",
	        lastName:  "Anderson",
	        age:       55,
	        salary:    6000,
	    }
	    fmt.Println("First Name:", (*emp8).firstName)
	    fmt.Println("Age:", (*emp8).age)
	}
	
	// First Name: Sam  
	// Age: 55 

6. Anonymous fields

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Person struct {  
	    string
	    int
	}
	
	func main() {  
	    p1 := Person{
	        string: "naveen",
	        int:    50,
	    }
	    fmt.Println(p1.string)
	    fmt.Println(p1.int)
	}

7. Nested structs

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Address struct {  
	    city  string
	    state string
	}
	
	type Person struct {  
	    name    string
	    age     int
	    address Address
	}
	
	func main() {  
	    p := Person{
	        name: "Naveen",
	        age:  50,
	        address: Address{
	            city:  "Chicago",
	            state: "Illinois",
	        },
	    }
	
	    fmt.Println("Name:", p.name)
	    fmt.Println("Age:", p.age)
	    fmt.Println("City:", p.address.city)
	    fmt.Println("State:", p.address.state)
	}
	
	
	// Name: Naveen  
	// Age: 50  
	// City: Chicago  
	// State: Illinois
go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type Address struct {  
	    city  string
	    state string
	}
	type Person struct {  
	    name string
	    age  int
	    Address
	}
	
	func main() {  
	    p := Person{
	        name: "Naveen",
	        age:  50,
	        Address: Address{
	            city:  "Chicago",
	            state: "Illinois",
	        },
	    }
	
	    fmt.Println("Name:", p.name)
	    fmt.Println("Age:", p.age)
	    fmt.Println("City:", p.city)   //city is promoted field
	    fmt.Println("State:", p.state) //state is promoted field
	}
	
	// Name: Naveen  
	// Age: 50  
	// City: Chicago  
	// State: Illinois  

9. Structs Equality

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	type name struct {  
	    firstName string
	    lastName  string
	}
	
	func main() {  
	    name1 := name{
	        firstName: "Steve",
	        lastName:  "Jobs",
	    }
	    name2 := name{
	        firstName: "Steve",
	        lastName:  "Jobs",
	    }
	    if name1 == name2 {
	        fmt.Println("name1 and name2 are equal")
	    } else {
	        fmt.Println("name1 and name2 are not equal")
	    }
	
	    name3 := name{
	        firstName: "Steve",
	        lastName:  "Jobs",
	    }
	    name4 := name{
	        firstName: "Steve",
	    }
	
	    if name3 == name4 {
	        fmt.Println("name3 and name4 are equal")
	    } else {
	        fmt.Println("name3 and name4 are not equal")
	    }
	}
	
	
	// name1 and name2 are equal  
	// name3 and name4 are not equal  

三、Methods

1. Sample Method

go 复制代码
	package main
	
	import (
		"fmt"
	)
	
	type Employee struct {
		name     string
		salary   int
		currency string
	}
	
	func (e Employee) displaySalary() {
		fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
	}	//   displaySalary() method has Employee as the receiver type
	
	func main() {
		emp1 := Employee{
			name:     "Like",
			salary:   9999,
			currency: "$",
		}
		emp1.displaySalary()
	}
	
	
	// Salary of Like is $9999

2. Pointer Receivers VS Value Receivers

go 复制代码
	package main
	
	import "fmt"
	
	type Employees struct {
		name string
		age  int
	}
	
	func (e Employees) changeName(newName string) { // 值接收器
		e.name = newName
	}
	func (e *Employees) changeAge(newAge int) { // 指针接收器 必须添加*号否则修改不成功
		e.age = newAge
	}
	
	func main() {
		e := Employees{
			name: "Like",
			age:  21,
		}
		fmt.Printf("Employees name brfore change: %s", e.name)
		e.changeName("XiaoXiao")
		fmt.Printf("\nEmployees name after change: %s", e.name)
		fmt.Printf("\nEmployees age brfore change: %d", e.age)
		//e.changeAge(18)
		(&e).changeAge(19) // &e使用指针的方法接收
		fmt.Printf("\nEmployees age after change: %d", e.age)
	}
	
	// Employees name brfore change: Like
	// Employees name after change: Like
	// Employees age brfore change: 21
	// Employees age after change: 19

3. Methods of anonymous struct fields

go 复制代码
	type address struct {
		city  string
		state string
	}
	
	func (a address) fullAddress() {
		fmt.Printf("Full address: %s, %s", a.city, a.state)
	}
	
	type person struct {
		firstName string
		lastName  string
		address
	}
	
	func main() {
		p := person{
			firstName: "Li",
			lastName:  "ke",
			address: address{
				city:  "Los Angeles",
				state: "California",
			},
		}
		p.fullAddress()
	}
	
	// Full address: Los Angeles, California

4. Value receivers in methods VS Value arguments in functions

go 复制代码
	type rectangle struct {
		length int
		width  int
	}
	
	func area(r rectangle) {
		fmt.Printf("Area Function result: %d\n", (r.length * r.width))
	}
	
	func (r rectangle) area() {
		fmt.Printf("Area Method result: %d\n", (r.length * r.width))
	}
	func main() {
		r := rectangle{
			length: 10,
			width:  5,
		}
	
		area(r)
		r.area()
		p := &r
		p.area()
	}
	
	// Area Function result: 50
	// Area Method result: 50
	// Area Method result: 50

5. Pointer receivers in methods VS Pointer arguments in functions

go 复制代码
	type rectangle struct {
		length int
		width  int
	}
	
	func perimeter(r *rectangle) {
		fmt.Println("perimeter function output:", 2*(r.length+r.width))
	}
	
	func (r *rectangle) perimeter() {
		fmt.Println("perimeter method output:", 2*(r.length+r.width))
	}
	func main() {
		r := rectangle{
			length: 10,
			width:  5,
		}
	
		p := &r //pointer to r
		perimeter(p)
		p.perimeter()
		r.perimeter() //calling pointer receiver with a value
	}
	
	// perimeter function output: 30
	// perimeter method output: 30
	// perimeter method output: 30

6. Methods with non-struct receivers

go 复制代码
	type myInt int
	
	func (a myInt) add(b myInt) myInt {
		return a + b
	}
	
	func main() {
		num1 := myInt(5)
		num2 := myInt(10)
		sum := num1.add(num2)
		fmt.Println("Sum is", sum)
	}
	
	// Sum is 15
相关推荐
IT技术分享社区9 分钟前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
极客代码12 分钟前
【Python TensorFlow】入门到精通
开发语言·人工智能·python·深度学习·tensorflow
疯一样的码农19 分钟前
Python 正则表达式(RegEx)
开发语言·python·正则表达式
代码之光_198019 分钟前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi25 分钟前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
疯狂的程需猿30 分钟前
一个百度、必应搜索引擎图片获取下载的工具包
golang·图搜索
&岁月不待人&41 分钟前
Kotlin by lazy和lateinit的使用及区别
android·开发语言·kotlin
StayInLove44 分钟前
G1垃圾回收器日志详解
java·开发语言
无尽的大道1 小时前
Java字符串深度解析:String的实现、常量池与性能优化
java·开发语言·性能优化
爱吃生蚝的于勒1 小时前
深入学习指针(5)!!!!!!!!!!!!!!!
c语言·开发语言·数据结构·学习·计算机网络·算法