2020年6月1日月曜日

開発環境

Go Systems Programming: Master Linux and Unix system level programming with Go (Mihalis Tsoukalos(著)、Packt Publishing)のChapter 2(Writing Programs in Go)、Exercises 9.の解答を求めてみる。

コード

package main

import "fmt"

func p(a, b []int) {
 for _, s := range [][]int{a, b} {
  fmt.Printf("%T %[1]v length: %v, capacity: %v\n", s, len(s), cap(s))
 }
}
func main() {
 a := []int{1, 2, 3, 4, 5}
 b := make([]int, 1, 2)
 fmt.Println("smaller")
 p(a, b)
 n := copy(b, a)
 fmt.Println(n)
 p(a, b)
 fmt.Println("bigger")
 c := make([]int, 10, 20)
 n = copy(c, a)
 fmt.Println(n)
 p(a, c)
}

入出力結果(Zsh、PowerShell、Terminal)

% go run main.go                            
smaller
[]int [1 2 3 4 5] length: 5, capacity: 5
[]int [0] length: 1, capacity: 2
1
[]int [1 2 3 4 5] length: 5, capacity: 5
[]int [1] length: 1, capacity: 2
bigger
5
[]int [1 2 3 4 5] length: 5, capacity: 5
[]int [1 2 3 4 5 0 0 0 0 0] length: 10, capacity: 20
%

0 コメント:

コメントを投稿