package main import "fmt" func main() { var a int = 10 fmt.Printf("Address of variable: %x\n", &a ) }
The format of pointer declaration is as follows:
var var_name *var-type
Pointer usage process:
- Define pointer variables.
- Assign values to pointer variables.
- Access the value pointing to the address in the pointer variable.
Add a * sign (prefix) before the pointer type to get the content pointed to by the pointer.
package main import "fmt" func main() { var a int= 20 /* Declare actual variables */ var ip *int /* Declare pointer variables */ ip = &a /* Storage address of pointer variable */ fmt.Printf("a The address of the variable is: %x\n", &a ) /* Storage address of pointer variable */ fmt.Printf("ip Pointer address of variable storage: %x\n", ip ) /* Accessing values using pointers */ fmt.Printf("*ip Value of variable: %d\n", *ip )
When a pointer is defined and not assigned to any variable, its value is nil.
nil pointers are also called null pointers.
Like null, None, nil and null in other languages, nil conceptually refers to zero value or null value.
A pointer variable is usually abbreviated as ptr.
Go language pointer array
package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int var ptr [MAX]*int; for i = 0; i < MAX; i++ { ptr[i] = &a[i] /* Assign integer address to pointer array */ } for i = 0; i < MAX; i++ { fmt.Printf("a[%d] = %d\n", i,*ptr[i] ) } }
Go language secondary pointer
package main import "fmt" func main() { var a int var ptr *int var pptr **int a = 3000 /* Pointer ptr address */ ptr = &a /* Pointer ptr address */ pptr = &ptr /* Gets the value of pptr */ fmt.Printf("variable a = %d\n", a ) fmt.Printf("Pointer variable *ptr = %d\n", *ptr ) fmt.Printf("Pointer variable to pointer **pptr = %d\n", **pptr)
Variable a = 3000 Pointer variable * ptr = 3000 Pointer variable pointing to pointer * * pptr = 3000
Go language pointer as function parameter
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 fmt.Printf("Before exchange a Value of : %d\n", a ) fmt.Printf("Before exchange b Value of : %d\n", b ) /* Call the function to exchange values * &a Address to a variable * &b Address to b variable */ swap(&a, &b); fmt.Printf("After exchange a Value of : %d\n", a ) fmt.Printf("After exchange b Value of : %d\n", b ) } func swap(x *int, y *int) { var temp int temp = *x /* Save the value of the x address */ *x = *y /* Assign y to x */ *y = temp /* Assign temp to y */ }
The contents of the pointer above are similar to those in C language, and the description will not be repeated.
Go language structure
In Go language, arrays can store the same type of data, but in the structure, we can define different data types for different items. A structure is a data set composed of a series of data of the same type or different types.
Structure definition requires type and struct statements. Struct statement defines a new data type with one or more members in the structure. The type statement sets the name of the structure.
The format of the structure is as follows:
type struct_variable_type struct { member definition member definition ... member definition }
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { // Create a new structure fmt.Println(Books{"Go language", "www.runoob.com", "Go Language course", 6495407}) // You can also use the format key = > value fmt.Println(Books{title: "Go language", author: "www.runoob.com", subject: "Go Language course", book_id: 6495407}) // The ignored field is 0 or empty fmt.Println(Books{title: "Go language", author: "www.runoob.com"}) }
{Go language www.runoob.com Go language tutorial 6495407} {Go language www.runoob.com Go language tutorial 6495407} {Go language www.runoob. Com 0}
Access structure members
If you want to access structure members, you need to use a point number . Operator in the format:
Structure. Member name
Structure type variables are defined with the struct keyword. Examples are as follows:
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 as a Books type */ var Book2 Books /* Declare Book2 as a Books type */ /* book 1 describe */ Book1.title = "Go language" Book1.author = "www.runoob.com" Book1.subject = "Go Language course" Book1.book_id = 6495407 /* book 2 describe */ Book2.title = "Python course" Book2.author = "www.runoob.com" Book2.subject = "Python Language course" Book2.book_id = 6495700 /* Print Book1 information */ fmt.Printf( "Book 1 title : %s\n", Book1.title) fmt.Printf( "Book 1 author : %s\n", Book1.author) fmt.Printf( "Book 1 subject : %s\n", Book1.subject) fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id) /* Print Book2 information */ fmt.Printf( "Book 2 title : %s\n", Book2.title) fmt.Printf( "Book 2 author : %s\n", Book2.author) fmt.Printf( "Book 2 subject : %s\n", Book2.subject) fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id) }
Structure as function parameter
Structure types can be passed as arguments to functions like other data types. And access the structure variable in the way of the above example:
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 as a Books type */ var Book2 Books /* Declare Book2 as a Books type */ /* book 1 describe */ Book1.title = "Go language" Book1.author = "www.runoob.com" Book1.subject = "Go Language course" Book1.book_id = 6495407 /* book 2 describe */ Book2.title = "Python course" Book2.author = "www.runoob.com" Book2.subject = "Python Language course" Book2.book_id = 6495700 /* Print Book1 information */ printBook(Book1) /* Print Book2 information */ printBook(Book2) } func printBook( book Books ) { fmt.Printf( "Book title : %s\n", book.title) fmt.Printf( "Book author : %s\n", book.author) fmt.Printf( "Book subject : %s\n", book.subject) fmt.Printf( "Book book_id : %d\n", book.book_id) }
Structure pointer
You can define a pointer to the structure, which is similar to other pointer variables. The format is as follows:
var struct_pointer *Books
The pointer variable defined above can store the address of the structure variable. To view the structure variable address, you can place the & symbol in front of the structure variable:
struct_pointer = &Book1
Use the structure pointer to access structure members, and use the "." operator:
struct_pointer.title
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 as a Books type */ var Book2 Books /* Declare Book2 as a Books type */ /* book 1 describe */ Book1.title = "Go language" Book1.author = "www.runoob.com" Book1.subject = "Go Language course" Book1.book_id = 6495407 /* book 2 describe */ Book2.title = "Python course" Book2.author = "www.runoob.com" Book2.subject = "Python Language course" Book2.book_id = 6495700 /* Print Book1 information */ printBook(&Book1) /* Print Book2 information */ printBook(&Book2) } func printBook( book *Books ) { fmt.Printf( "Book title : %s\n", book.title) fmt.Printf( "Book author : %s\n", book.author) fmt.Printf( "Book subject : %s\n", book.subject) fmt.Printf( "Book book_id : %d\n", book.book_id) }
Inline structure
In addition to defining new types that represent structures, you can also define inline structures. These dynamic structure definitions are useful when wasting new names for structure types. For example, tests typically use structures to define all the parameters that make up a particular test case. When you use this structure in only one place, it's cumbersome to come up with a new name like createnameprintingtestcase.
The inline structure definition appears to the right of the variable assignment. You must instantiate each defined field immediately after providing another pair of parentheses with values. The following example shows the inline structure definition:
package main import "fmt" func main() { c := struct { Name string Type string }{ Name: "Sammy", Type: "Shark", } fmt.Println(c.Name, "the", c.Type) }
Go language slice
Go language slicing is an abstraction of arrays.
The length of the go array cannot be changed, and such a collection is not applicable in a specific scene. Go provides a flexible and powerful built-in type slice ("dynamic array"). Compared with the array, the length of the slice is not fixed, and elements can be added, which may increase the capacity of the slice.
You can define slices by declaring an array of unspecified size:
var identifier []type
The slice does not need to specify the length.
Or use make() Function to create a slice:
var slice1 []type = make([]type, len) It can also be abbreviated as: slice1 := make([]type, len)
You can also specify the capacity, where capacity Is an optional parameter.
make([]T, length, capacity)
Here len is the length of the array and is also the initial length of the slice.
Slice initialization
s :=[] int {1,2,3 }
Initialize slice directly, [] Indicates the slice type, {1,2,3} The initialization values are 1,2,3, its cap=len=3.
s := arr[:]
Initialize slice s. Is a reference to array arr.
s := arr[startIndex:endIndex]
Create a new slice of the elements in arr from the subscript startIndex to endIndex-1.
s := arr[startIndex:]
The default startIndex will indicate starting from the first element of the arr.
s := arr[:endIndex]
By default, endIndex will represent the last element up to arr.
s1 := s[startIndex:endIndex]
Initialize slice s1 by slice s.
s :=make([]int,len,cap)
Through built-in functions make() Initialize slice s, [] int Identifies the slice whose element type is int.
value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|---|
Positive index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Negative index | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
len() and cap() functions
Slices are indexable, and the length can be obtained by the len() method.
Slicing provides a method to calculate the capacity. cap() can measure the maximum length of slicing.
package main import "fmt" func main() { var numbers = make([]int,3,5) printSlice(numbers) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
The output results of the above examples are:
len=3 cap=5 slice=[0 0 0]
Empty (nil) slice
package main import "fmt" func main() { var numbers []int printSlice(numbers) if(numbers == nil){ fmt.Printf("The slice is empty") } } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
len=0 cap=0 slice=[] The slice is empty
Slice interception
You can set the cut slice by setting the lower and upper limits [lower-bound:upper-bound]
package main import "fmt" func main() { /* Create slice */ numbers := []int{0,1,2,3,4,5,6,7,8} printSlice(numbers) /* Print original slice */ fmt.Println("numbers ==", numbers) /* Print sub slice from index 1 (included) to index 4 (not included)*/ fmt.Println("numbers[1:4] ==", numbers[1:4]) /* The default lower limit is 0*/ fmt.Println("numbers[:3] ==", numbers[:3]) /* The default upper limit is len(s)*/ fmt.Println("numbers[4:] ==", numbers[4:]) numbers1 := make([]int,0,5) printSlice(numbers1) /* Print sub slice from index 0 (included) to index 2 (not included) */ number2 := numbers[:2] printSlice(number2) /* Print sub slice from index 2 (included) to index 5 (not included) */ number3 := numbers[2:5] printSlice(number3) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
Execute the above code and the output result is:
len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8] numbers == [0 1 2 3 4 5 6 7 8] numbers[1:4] == [1 2 3] numbers[:3] == [0 1 2] numbers[4:] == [4 5 6 7 8] len=0 cap=5 slice=[] len=2 cap=9 slice=[0 1] len=3 cap=7 slice=[2 3 4]
append() and copy() functions
If we want to increase the capacity of the slice, we must create a new and larger slice and copy the contents of the original slice.
The following code describes the copy method for copying slices and the append method for appending new elements to slices.
package main import "fmt" func main() { var numbers []int printSlice(numbers) /* Allow appending empty slices */ numbers = append(numbers, 0) printSlice(numbers) /* Add an element to the slice */ numbers = append(numbers, 1) printSlice(numbers) /* Add multiple elements at the same time */ numbers = append(numbers, 2,3,4) printSlice(numbers) /* Creating slice numbers1 is twice the capacity of the previous slice*/ numbers1 := make([]int, len(numbers), (cap(numbers))*2) /* Copy the contents of numbers to numbers1 */ copy(numbers1,numbers) printSlice(numbers1) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
The output result of the above code execution is:
len=0 cap=0 slice=[] len=1 cap=1 slice=[0] len=2 cap=2 slice=[0 1] len=5 cap=6 slice=[0 1 2 3 4] len=5 cap=12 slice=[0 1 2 3 4]