lemonadern's golang learning history #3
Replies: 15 comments 31 replies
-
Named return values返り値のところに名前をつけることができる func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
} 可読性を損なうので、短い関数でのみ利用すべき |
Beta Was this translation helpful? Give feedback.
-
Variables
var a, b, c bool
var i, j int = 1, 2 |
Beta Was this translation helpful? Give feedback.
-
型変換型 |
Beta Was this translation helpful? Give feedback.
-
定数const Pi = 3.14
|
Beta Was this translation helpful? Give feedback.
-
For
sum := 0
for i := 0; i < 11; i++ {
sum += i
} 真ん中の statement だけでも記述できる sum := 1
for ; sum < 1000; {
sum += sum
} |
Beta Was this translation helpful? Give feedback.
-
If
if x < 0 {
return "i"
} |
Beta Was this translation helpful? Give feedback.
-
SwitchIf のように、そのスコープで有効なstatementを条件式の前に書ける。セミコロンで区切る switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
} マッチした場合はそこでswitch から抜けるので、Cのように |
Beta Was this translation helpful? Give feedback.
-
deferdefer を利用すると、関数の値を返すのを、呼び出し元の関数が終了するまで遅らせる 関数の評価自体はコードの順に行われており、返すときだけが遅らせられる |
Beta Was this translation helpful? Give feedback.
-
Pointer
// ポインタ *T
var p *int
// &v で v のポインタ
i := 42
p = &i
// *p で、ポインタpが指す先にある変数
*p = 21 |
Beta Was this translation helpful? Give feedback.
-
Structs
type Vertex struct {
X int
Y int
} 初期化 v := Vertex{1, 2} アクセス v.X = 4 |
Beta Was this translation helpful? Give feedback.
-
Array
var arr [4]int 値を入れて初期化する場合、 primes := [6]int{2, 3, 5, 7, 11, 13}
|
Beta Was this translation helpful? Give feedback.
-
Mapkey-value の関係 var m map[string]string
m = make map[string]string |
Beta Was this translation helpful? Give feedback.
-
Function ClosuresGo における関数はクロージャ func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-1*i),
)
}
} adder は クロージャを返す |
Beta Was this translation helpful? Give feedback.
-
MethodsGo では、型にメソッドを定義できる
type Vertex struct {
x, y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.x*v.x + v.y*v.y)
} |
Beta Was this translation helpful? Give feedback.
-
Interfacesメゾッドのシグニチャを与えて定義する type Abser interface {
Abs() float64
} interface は暗黙的に実装する (implemented implicitly) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
はじめます
気になったところとか、初めて知ったところを中心に残す
Beta Was this translation helpful? Give feedback.
All reactions