What is a tuple in go language?

青灯夜游
Release: 2022-12-27 11:27:27
Original
4923 people have browsed it

Tuples are fixed-length immutable sequential containers (element sequences). There is no tuple type in the Go language, and arrays are equivalent to tuples. In the Go language, an array is a sequence composed of fixed-length elements of a specific type. An array can be composed of zero or more elements; the declaration syntax of an array is "var array variable name [number of elements]Type".

What is a tuple in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

What is a tuple

Tuple (tuple): a fixed-length immutable sequential container with high access efficiency and suitable for storing some long constant data.

The simple understanding is to store a bunch of data in a container, but this container has a characteristic, that is, it is very stubborn. Once it is defined, it cannot be changed. In a sense, tuples cannot The function of the changed list is similar to that of the list, and operations such as slicing and modification can also be performed.

There is no tuple type in Go language

Arrays in Go language are equivalent to tuples in Python.

An array is a sequence of fixed-length elements of a specific type. An array can consist of zero or more elements.

Arrays in Go language

Declaration of arrays

The declaration syntax of arrays is as follows:

var 数组变量名 [元素数量]Type
Copy after login

The syntax description is as follows:

  • Array variable name: The variable name when the array is declared and used.

  • Number of elements: The number of elements of the array can be an expression, but the final result calculated at compile time must be an integer value. The number of elements cannot be included until runtime to confirm the size. value.

  • Type: It can be any basic type, including the array itself. When the type is the array itself, multi-dimensional arrays can be implemented.

In the Go language, to create an array, you can declare an array variable and specify its length and data type.

only contains two elements, and the third element cannot be assigned a value, so this will cause a compilation phase error.

var cheeses [2]string
cheeses[O] = "Mar iolles”
cheeses[l] = ” Epoisses de Bourgogne ”
Copy after login

Each element of the array can be accessed through the index subscript. The range of the index subscript is from 0 to the length of the array minus 1. The built-in function len() can return the number of elements in the array. .

var a [3]int             // 定义三个整数的数组
fmt.Println(a[0])        // 打印第一个元素
fmt.Println(a[len(a)-1]) // 打印最后一个元素
// 打印索引和元素
for i, v := range a {
    fmt.Printf("%d %d\n", i, v)
}
// 仅打印元素
for _, v := range a {
    fmt.Printf("%d\n", v)
}
Copy after login

By default, each element of the array will be initialized to the zero value corresponding to the element type, which is 0 for numeric types. At the same time, you can also use the array literal syntax to initialize with a set of values. Array:

var q [3]int = [3]int{1, 2, 3}
var r [3]int = [3]int{1, 2}
fmt.Println(r[2]) // "0"
Copy after login

In the definition of the array, if the "..." ellipsis appears in the position of the array length, it means that the length of the array is calculated based on the number of initialization values. Therefore, the above array q The definition can be simplified to:

q := [...]int{1, 2, 3}
fmt.Printf("%T\n", q) // "[3]int"
Copy after login

The length of the array is an integral part of the array type, so [3]int and [4]int are two different array types. The length of the array must be a constant expression, Because the length of the array needs to be determined at the compilation stage.

q := [3]int{1, 2, 3}
q = [4]int{1, 2, 3, 4} // 编译错误:无法将 [4]int 赋给 [3]int
Copy after login

Compare two arrays for equality

If the two arrays have the same type (including the length of the array and the type of elements in the array), we can directly Use comparison operators (== and !=) to determine whether two arrays are equal. The arrays are equal only when all elements of the two arrays are equal. Two arrays of different types cannot be compared, otherwise the program will Unable to complete compilation.

a := [2]int{1, 2}
b := [...]int{1, 2}
c := [2]int{1, 3}
fmt.Println(a == b, a == c, b == c) // "true false false"
d := [3]int{1, 2}
fmt.Println(a == d) // 编译错误:无法比较 [2]int == [3]int
Copy after login

Traverse the array - access each array element

Traversing the array is also similar to traversing the slice. The code is as follows:

var team [3]string
team[0] = "hammer"
team[1] = "soldier"
team[2] = "mum"
for k, v := range team {
    fmt.Println(k, v)
}
Copy after login

Code output Result:

What is a tuple in go language?

The code description is as follows:

  • Line 6, use a for loop to traverse the team array and traverse the key k is the index of the array, and the value v is the value of each element of the array.

  • Line 7, print out each key value.

Implementing the tuple function in Golang

Although other languages ​​have tuple types, the go language not offered. But there is no need to despair, other features of go make it very easy to implement tuple functions. The following example demonstrates how Go implements tuple type functions.

Using struct

tuple can store different data types. We can use the interface{} type to support any data type.

package main

import "fmt"

func main() {
	type Student struct {
		name, age interface{}
	}

	stuList1 := []Student{
		{"tom", 21},
		{"jack", 22},
	}

	stuList2 := []Student{
		{"mary", 30},
	}
	// append stuList2 to stuList1
	stuList1 = append(stuList1, stuList2...)

	for _, stu := range stuList1 {
		fmt.Println(“stuInfo:”,stu)
	}
}


/*
Output:
stuInfo: {tom 21}
stuInfo: {jack 22}
stuInfo: {mary 30}
*/
Copy after login

You can see through the output that the result is similar to a tuple type, and you can also access individual attributes through the dot. Although these features are related to tuple, it is not actually a tuple type.

Return multiple values

You can return multiple values ​​through the tuple function. Although go does not have a tuple type, it supports returning functions to return multiple values:

package main

import "fmt"

func multipleValues() (string, int) {
	return "Alex", 21
}

func main() {
	name, age := multipleValues()
	fmt.Println("Name :", name)
	fmt.Println("Age :", age)
}

/*
Output:
Name : Alex
Age : 21
*/
Copy after login

Here you can see that multiple values ​​are returned at one time.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What is a tuple in go language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template