Tuesday, April 19, 2022

Go vs Rust - Tuple

 Tuple

A tuple is a collection of values of different types. Functions can use tuples to return multiple values, as tuples can hold any number of values.

Go 

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. 

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)
}

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.

package main

import "fmt"
func multipleValues() (string, int) {
return "Alex", 21
}
func main() {
name, age := multipleValues()
fmt.Println("Name :", name)
fmt.Println("Age :", age)
}

Rust

let long_tuple = (1u8, 2u16); 
// Values can be extracted from the tuple using tuple indexing
println!("long tuple first value: {}", long_tuple.0);
println!("long tuple second value: {}", long_tuple.1);
   
// Tuples can be tuple members
let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);

//tuples can be destructured to create bindings
let tuple = (1, "hello", 4.5, true);
let (a, b, c, d) = tuple;
println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);



No comments:

Post a Comment