You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main
import (
"fmt""math/rand"
)
funcmain() {
fmt.Println("My favorite number is", rand.Intn(10))
}
Imports
This code groups the imports into a parenthesized, factored import statement.
package main
import (
"fmt""math"
)
funcmain() {
fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
}
Exported names
In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package.
When importing a package, you can refer only to its exported names. Any "unexported" names are not accessible from outside the package.
Functions
A function can take zero or more arguments.
Notice that the type comes after the variable name.
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
x int, y int → x, y int
Multiple results
A function can return any number of results.
funcswap(x, ystring) (string, string) {
returny, x
}
funcmain() {
a, b:=swap("hello", "world")
fmt.Println(a, b)
}
Named return values
Go's return values may be named. If so, they are treated as variables defined at the top of the function.
These names should be used to document the meaning of the return values.
A return statement without arguments returns the named return values. This is known as a "naked" return.
Naked return statements should be used only in short functions, as with the example shows here. They can harm readability in longer functions.
rune (alias for int32, represents a Unicode code point)
float32, float64
complex64, complex128
Zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
0 for numeric types
false for the boolean type
"" (the empty string) for strings
Type conversions
The expression T(v) converts the value v to the type T.
Unlike in C, in Go assignment between items of different type requires an explicit conversion.
funcmain() {
varx, yint=3, 4varffloat64=math.Sqrt(float64(x*x+y*Y))
varzuint=uint(f)
fmt.Println(x, y, z)
}
Type inference
When declaring a variable without sepcifiying an explicit type (either by using the := syntax or var = expression syntax), the variable's type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
variintj:=i// j is an int
Constants
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
The basic for loop has three components separated by semicolons:
The init statement: executed before the first iteration.
The condition expression: evaluated before every iteration.
The post statement: executed at the end of every iteration.
Note: Unlike other languages like C, Java, or JavaScript there are no parenthes surroudning the three components of the for statement and the braces {} are always required.
Variables declared inside an if short statement are also available inside any of the else blocks.
funcpow(x, n, limfloat64) float64 {
ifv:=math.Pow(x, n); v<lim {
returnv
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, thoughreturnlim
}
Switch
A switch statement is a shorter way to write a sequence of if-else statements. It runs the first case whose value is equal to the condition.
Go's switch is like the one in C, C++, Java, JS, and PHP, except that Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case n those languages is provided automatically in Go.
When a function returns, its deferred called are executed in last-in-first-out order.
Pointers
Go has pointers. A pointer holds the memory address of a value.
The type *T is a pointer to a T value. Its zero value is nil.
The & operator generates a pointer to its operand.
The * operator denotes the pointer's underlying value. This is known as "dereferencing" or "indirecting".
Unlike C, Go has no pointer arithmetic.
Pointers (2)
funcmain() {
i, j:=42, 2701p:=&i// point to ifmt.Println(*p) // read i through the pointer*p=21// set i through the pointerfmt.Println(i) // see the new value of ip=&j// point to j*p=*p/37// divide j through the pointerfmt.Println(j) // see the new value of j
}
Struct fields can be accessed through a struct pointer.
To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit deference.
An arary's length is part of its type, so arrays cannot be resized. This seems limiting, but don't worry; Go provides a convenient way of working with arrays.
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.
The type []T is a slice with elements of type T.
A slice is formed by specifying two indices, a low and high bound, separated by a colon: a[low : high].
Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.
Changing the elements of a slice modifiers the corresponding elements of its underlying array.
Other slices that share the same underlying array will see those changes.
Slice Literals
A slice literal is like an array literal without the length.
This is an arrayliteral:
[3]bool{true, true, false}
And this creates the same array as above, then builds a slice that references it:
[]bool{true, true, false}
Slice defaults
When slicing, you may omit the high or low bounds to use their defaults instead.
The default is zero for the low bound and the length of the slice for the high bound.
These slice expressions are equivalent:
a[0:10] =a[:10] =a[0:] =a[:]
Slice length and capacity
A slice has both a length and a capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).
You can extend a slice's length by re-slicing it, provided it has sufficient capacity.
Nil slices
The zero value of a slice is nil.
A nil slice has a length and capacity of 0 and has no underlying array.
Slices can contain any type, including other slices.
// Create a tic-tac-toe board.board:= [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
// The players take turnsboard[0][0] ="X"board[2][2] ="O"board[1][2] ="X"board[1][0] ="O"board[0][2] ="X"
Appending to a slice
It is common to append new elements to a slice, and so Go provides a built-in append function.
It the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
// append works on nil slicess=append(s, 0)
// The slice grows as needed.s=append(s, 1)
// We can add more than one element at a time.s=append(s, 2, 3, 4)
Range
The range from of the for loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
// insert or update an element in map mm[key] =elem// retrieve an elementelem=m[key]
// delete an elementdelete(m, key)
// Test that a key is present with a two-value assignmentelem, ok=m[key]
Mutating Maps(2)
Note: If elem or ok have not yet been declared you could use a short declaration from:
elem, ok:=m[key]
Function values
Functions are values too. They can be passed around just like other values.
Function values may be used as function arguments and return values.
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
The first is so that the method can modify the value that its receiver points to.
The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.
In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
Interfaces
An interface type is defined as a set of method signatures.
A value of interface type can hold any value that implements those methods.
typeAbserinterface {
Abs() float64
}
Interfaces are implemented implicitly
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword.
Implicit interfaces decouple the definition of an interface from its implkementation, which could then appear in any package without prearrangement.
Interfaces are implemented implicitly
typeIinterface {
M()
}
typeTstruct {
Sstring
}
// This method means type T implements the interface I,// but we don't need to explicitly declare that it does so.func (tT) M() {
fmt.Println(t.S)
}
Interface values
Under the hood, interface values can be thought of as a tuple of a value and a concrete type:
(value, type)
An interface value holds a value of a specific underlying concrete type.
Calling a method on an interface value executes the method of th same name on its underlying type.
Interface values with nil underlying values
If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.
In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver.
Note that an interface value that holds a nil concrete value is itself non-nil.
Nil interface values
A nil interface value holds neither value nor concreate type.
Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.
The empty interface
The interface type that specifies zero methods is known as the empty interface:
interface{}
An empty interface may hold values of any type. (Every type implements at least zero methods.)
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.
Type assertions
A type assertion provides access to an interface value's underlying concreate value.
t:=i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
Type assetions (2)
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion.
t, ok:=i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
Type switches
A type switch is a construct that permits several type assertions in series.
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
switchv:=i.(type) {
caseT:
// here v has type TcaseS:
// here v has type Sdefault:
// no match; here v has the same type as i
}
Stringers
One of the most ubiquistous interfaces is Stringers defined by the fmt package.
typeStringerinterface {
String() string
}
A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.
Errors
Go programs express error state with error values.
The error type is a built-in interface similar to fmt.Stringer.
typeerrorinterface {
Error() string
}
Errors (2)
Functions often return an error value, and calling code should handle errors by testing whether the error equals nil.
A nil error denotes success; a non-nil error denotes failure.
Generics
Type parameters
Go functions can be written to work on multiple types using type parameters. The type parameters of a function appear between brackets, before the function's argumetns.
funcIndex[Tcomparable](s []T, xT) int
This declaration means that s is a slice of any type T that fulfills the built-in constraint comparable. x is also a value of type same type.
comparable is a useful constraint that makes it possible to use the == and != operators on values of the type.
Generic types
In addition to generic functions, Go also supports generic types. A type can be parameterized with a type parameter, which could be useful for implementing generic data structures.
// List represents a singly-linked list that holds// values of any type.typeList[Tany] struct {
next*List[T]
valT
}
Concurrency
Goroutines
A goroutines is a lightweight thread managed by the Go runtime.
gof(x, y, z)
The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.
Goroutines run in the same address space, so access to shared memory must be synchronized. The sync package provides useful primitives, although you won't need them much in Go as there are other primitives.
Channels
Channels are a typed conduit through which you can send and receive values with the channel operator, <-.
ch<-v// Send v to channel ch.v:=<-ch// Receive from ch, and assign value to v.
Like maps and slices, channels must be created befeore use:
ch:=make(chanint)
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
Buffered Channels
Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channels:
ch:=make(chanint, 100)
Sends to buffered channel block only when the buffer is full. Receives block when the buffer is empty.
Range and Close
A sender can close a channel to indicate that no more values will be sent. Receivers can that whether a channel has been closed by assigning a second parameter to the receive expression:
v, ok:=<-ch
ok is false if there are no more values to receive and the channel is closed.
The loop for i := range c receives values from the channel repeatedly until it is closed.
Only the sender should close a channel, never the receiver.
Select
The select statement let's a goroutine wait on multiple communication operations.
A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
The default case in a select is run if no other case is ready.
Use a default case to try a send or receive without blocking:
select {
casei:=<-c:
// use idefault:
// receiving from c would block
}
sync.Mutex
Go's standard library provides mutual exclusion with sync.Mutex andits two methods: Lock, Unlock:
// SafeCounter is safe to use concurrently.typeSafeCounterstruct {
mu sync.Mutexvmap[string] int
}
// Inc increments the counter for the given key.func (c*SafeCounter) Inc(keystring) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.c.v[key]++c.mu.Unlock()
}
Testing
テストファイルの作成
テストファイルはテストしたファイル名に _test を付けた名前で作成する.
テスト関数は TestXXX とCamel方式で書く.
テストの実行はコマンドラインで test を指定.
# テスト実行
go test<path> [-v]
# 特定のテストだけ実行したい場合
go test<path> [-v] -run <pattern># テストのキャッシュを削除したい場合
go test<path> [-v] -count=1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters