How to use tuple in Golang
In this article, you are going to learn about how to use tuples in the Go language.
In general, a sequence of finite ordered elements is considered as a tuple and in programming languages, a tuple means pair or an ordered set of values. Depending on the rules of particular programming languages, the values of a tuple can be separated by using a comma or any other syntax. Basically, in a tuple, you can store different types of data types and it is immutable.
Though some other programming languages have a tuple type, there is no tuple type in the Go language. That means you can not use tuple type in your Go program but you may implement some of its functionality by following a few approaches. You have already know about what a tuple is, now let’s see how you can implement it in the Go Language.
package main
import "fmt"
type Student struct {
name, age interface{}
}
func main() {
student1 := Student{"Alex", 21}
student2 := Student{"Alia", 18}
fmt.Println("student1 Info :", student1, "Student2 Info :", student2)
fmt.Println("Student1 Age :", student1.age)
fmt.Println("Student2 Name :", student2.name)
}
/*
Output:
student1 Info : {Alex 21} Student2 Info : {Alia 18}
Student1 Age : 21
Student2 Name : Alia
*/
Here, you can see that we are using two different data types like one is a string and another is an integer type with the help of an interface(). The output is showing that we can print data as a pair and moreover we can also access one single property from the data by using a dot. Though these characteristics are relatable with a tuple, this is not an actual tuple.
In a tuple, you can also return multiple values. Though Go language does not have any tuple type, you may apply it with the help of a function that returns multiple values. See the below code example:
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
*/
Here, you can see that we can return different types of values at a single time. These are some approaches and by following these you may apply a tuples characteristics in the Go language.