Menu
CoddyTech

構造体の値

Coddyの「Python開発者のためのGo」コースのレッスン 25/48。

Pythonでは、クラスのインスタンスを代入すると通常は同じオブジェクトを参照します。dataclassは代入のセマンティクスを変えません。Goでは、structの代入によってフィールドがコピーされます。ポインター、マップ、スライスのフィールド内にある参照先のデータは、コピー後も共有されることがあります。

structは、名前と固定された型を持つフィールドをまとめたものです。キー付きリテラルでは、設定するフィールド名を指定します。省略されたフィールドにはゼロ値が設定されます。代入ではstructの値がコピーされますが、その中のポインター、スライス、マップのフィールドが共有データを参照したままの場合があります。

Pythonの例

from dataclasses import dataclass, replace
@dataclass
class Label:
    text: str
a = Label("old")
b = replace(a)
b.text = "new"
print(a.text, b.text)

実行結果:

old new

Goの例

package main
import ("fmt")
type Label struct { Text string }
func main(){a:=Label{Text:"old"}
b:=a
b.Text="new"
fmt.Println(a.Text,b.Text)}

Goの実行結果:

old new
challenge icon

チャレンジ

簡単

エクスポートされた int フィールド Left と Right を持つ Pair を定義します。Solve はその合計を返します。入力の x と y は別々の行にあります。

宣言された API を実装し、出力を表示せずに結果を返してください。ドライバーは必要な API を確認し、呼び出し元の入力を保持します。コレクションの標準出力には JSON ではなく、Go の角括弧形式が使われます。

コードは pair.go と exercise.go に記述します。main.go には用意された入出力コードがあり、編集できません。フラットな package main を1つだけ使い、2つ目の main は追加しないでください。

自分で試してみよう

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
a1:=I(1); before1:=fmt.Sprint(a1)
p:=Pair{Left:4,Right:9}; q:=p; q.Left=0; must(p.Left==4 && p.Right==9,"struct value");
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Python開発者のためのGoのすべてのレッスン

自分で練習してみよう: Goオンラインコンパイラ