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

目录标题

  • 一、Pointer
    • 1. Declaring pointers
    • 2. Zero value of a pointer
    • 3. Creating pointers using the new function
    • 4. Dereferencing a pointer
    • 5. Passing pointer to 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.
    • 8. Go does not support pointer arithmetic
  • 二、Structs
    • 1. Creating named structs
    • 2. Creating anonymous structs
    • 3. Accessing individual fields of a struct
    • 4. Zero value of a struct
    • 5. Pointers to a struct
    • 6. Anonymous fields
    • 7. Nested structs
    • 8. Promoted fields
    • 9. Structs Equality
  • 三、Methods
    • 1. Sample Method
    • 2. Pointer Receivers VS Value Receivers
    • 3. Methods of anonymous struct fields
    • 4. Value receivers in methods VS Value arguments in functions
    • 5. Pointer receivers in methods VS Pointer arguments in functions
    • 6. Methods with non-struct receivers

一、Pointer

1. Declaring pointers

	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

	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 
	// b after initialization is 0xc0000180c8

3. Creating pointers using the new function

	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

	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

	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

	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.

	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

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


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

二、Structs

1. Creating named structs

	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

	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

	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

	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

	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

	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

	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

8. Promoted fields

	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

	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

	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

	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

	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

	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

	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

	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

你可能感兴趣的:(Go,golang,开发语言,后端,go)