[Go] Variables, Functions その2

#### function
– Named return values
names should be used to document the meaning of the return values.

func split(sum int)(x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

func main(){
	fmt.Println(split(17))
}

$ go build hello.go && ./hello
7 10

### Variables
The var statement declares a list of variables, as in function argument lists, the type is last.

var c, python, java bool

func main(){
	var i int
	fmt.Println(i, c, python, java)
}

initializer
short variable
L inside a function, the := short assignment statement can be used in place of var declaration with implicit type.

var i, j int = 1, 2

func main(){
	var c, python, java = true, false, "no!"
	k := 3
	fmt.Println(i, j, k, c, python, java)
}

$ go build hello.go && ./hello
1 2 3 true false no!

Basic types
L bool, string, int, uint, byte, rune, float32, float64, complex64, complex128

import (
	"fmt"
	"math/cmplx"
)

var (
	ToBe bool = false
	MaxInt uint64 = 1<<64 -1
	z complex128 = cmplx.Sqrt(-5 + 12i)
)

func main(){
	fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
	fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
	fmt.Printf("Type: %T Value: %v\n", z, z)
}

$ go build hello.go && ./hello
Type: bool Value: false
Type: uint64 Value: 18446744073709551615
Type: complex128 Value: (2+3i)

Zero values

package main
import "fmt"

func main(){
	var i int
	var f float64
	var b bool
	var s string
	fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

$ go build hello.go && ./hello
0 0 false “”

Type conversions
– The expression T(v) converts the value v to the type T.

import (
	"fmt"
	"math"
)

func main(){
	var x, y int = 3, 4
	var f float64 = math.Sqrt(float64(x*x + y*y))
	var z uint = uint(f)
	fmt.Println(x, y, z)
}

$ go build hello.go && ./hello
3 4 5

Type inference
– The variable’s type is inferred from the value on the right hand side.

func main(){
	v := 42
	fmt.Printf("v is of type %T\n", v)
}

$ go build hello.go && ./hello
v is of type int

Constants
– constants are declared like variables, but with the const keyword.

const Pi = 3.14

func main(){
	const World = "世界"
	fmt.Println("Hello", World)
	fmt.Println("Hello", Pi, "Day")

	const Truth = true
	fmt.Println("Go rules", Truth)
}

$ go build hello.go && ./hello
Hello 世界
Hello 3.14 Day
Go rules true

Numeric Constants

const (
	Big = 1 << 100
	Small = Big >> 99
)

func needInt(x int) int {return x*10 + 1}
func needFloat(x float64) float64 {
	return x * 0.1
}

func main(){
	fmt.Println(needInt(Small))
	fmt.Println(needFloat(Small))
	fmt.Println(needFloat(Big))
}

$ go build hello.go && ./hello
21
0.2
1.2676506002282295e+29

ふう…
英語だと変な脳みそ使うね