[Go] Packages, Variables, Functions その1

Every Go is made up of packages. Programs start running in package main.

package main
import(
	"fmt"
	"math/rand"
) 

func main(){
	fmt.Println("My favorite number is", rand.Intn(10))
}

$ go build hello.go && ./hello
My favorite number is 1

### import
“factored” import statement

import(
	"fmt"
	"math"
) 

func main(){
	fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
}

$ go build hello.go && ./hello
Now you have 2.6457513110645907 problems.

### Exported names
A name is exported if it begins with a capital letter
it can not be used “math.pi”

import(
	"fmt"
	"math"
) 

func main(){
	fmt.Println(math.Pi)
}

### Functions
A function can take zero or more arguments.
The type comes after variable name.

func add(x int, y int) int {
	return x + y
}

func main(){
	fmt.Println(add(22, 34))
}

$ go build hello.go && ./hello
56

When two or more consecutive named function parameters share a type, can omit the type from all but the last

func add(x, y int) int {
	return x + y
}

function can return any number of results

func swap(x, y string)(string, string) {
	return y, x
}

func main(){
	a, b := swap("hello", "go")
	fmt.Println(a, b)
}

$ go build hello.go && ./hello
go hello

おおお、なんか凄いな