Ccmmutty logo
Commutty IT
2 min read

Tuples

https://cdn.magicode.io/media/notebox/4515eccf-fdd7-419d-a9f3-bcd56ea5b08f.jpeg
タプルとは、有限のソートされた要素のリストのことです。データをグループ化するデータ構造である。タプルは通常、不変のシーケンシャル・コレクションです。要素は、異なるデータ型の関連フィールドを持っています。タプルを変更するには、フィールドを変更するしかありません。タプルには、+*などの演算子を適用できます。データベースのレコードはタプルと呼ばれます。次の例では、整数の累乗を計算し、その平方と立方をタプルとして返しています。
go
// importing fmt package
import (
"fmt"
)
//gets the power series of integer a and returns tuple of square of a
// and cube of a
func powerSeries(a int) (int,int) {
     return a*a, a*a*a
}

func main(){
    var square int
    var cube int
    square, cube = powerSeries(3)

    fmt.Println("Square ", square, "Cube", cube)
}

main()
返すtupleには中身の名前を指定すればそのまま返せるらしい。
go
func powerSeries(a int) (square int, cube int) {
    square = a*a
    cube = square*a
    return
}
エラーが発生すればそれをtupleに渡せる。
go
func powerSeries(a int) (int, int, error) {
    square = a*a
    cube = square*a
    return square, cube, nil
}

Discussion

コメントにはログインが必要です。