go言語
- 公開日:
- 更新日:
- 文字数:3380文字
https://golang.org/
ダウンロード
https://godoc.org/golang.org/x/tools/cmd/godoc
go get golang.org/x/tools/cmd/godoc
`
バッククオート
stringからintに変えれない
strconvが必要
文字列とバイトは互換性があるのでcastができる
スライス、make,append
var a []int
a := make([]int, 3, 6)
第1引数タイプ
第2引数len
第3引数キャップ
map
pythonのディクショナリー型といっしょ
map[string]int{"appale": 100, " banana": 200}
var a3 map[string]int
a3["aaa"] = 1000
上記はエラーになる
a3 := map[string]int{}
a3["aaa"] = 1000
上記はエラーにならない
func関数の書き方
func add(x int, y int) int{
return x + y
}
func add_1(x, y int)(int, int){
return x + y, x - y
}
func add_2(x, y int)(result int){
result = x * y
return
}
クロージャー
func circle(pi float64) func(radius float64) float64{
return func(radius float64) float64{
return pi radius radius
}
}
c1 := circle(3.14)
fmt.Println(c1(2))
可変長引数
func foo(params ...int){
fmt.Println(len(params), params)
for _, param := range params{
fmt.Println(param)
}
}
ログ設定
func LoggingSettings(logFile string){
logfile, _ := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
multiLogFile := io.MultiWriter(os.Stdout, logfile)
log.SetFlags(log.Ldate | log.Ltime | log.Llongfile)
log.SetOutput(multiLogFile)
}
main関数に
LoggingSettings("test.log")
new と makeの違い
pointerを返すか返さないか
ポイントレシーバー
アタイレシーバー
type Vertex struct {
X, Y int
Z string
}
//ポイントレシーバー
func (v Vertex) Scale(i int){
v.X = v.X i
v.Y = v.Y i
}
//アタイレシーバー
func (v Vertex) Area() int{
return v.X v.Y
}
コストラスク
エムベレットなぞ
インターフェイス
制限をする
switch type文
switch v := i.(type){
case int:
case string:
defult:
;;;;;
}
自分のエラー関数をつくるときは
- &をつける
package main
import "fmt"
type UserNotFound struct {
Username string
}
func (e *UserNotFound) Error() string{
return fmt.Sprintf("User not found: %v", e.Username)
}
func myFunc() error{
ok := false
if ok {
return nil
}
return &UserNotFound{Username: "mike"}
}
func main(){
if err := myFunc(); err != nil{
fmt.Println(err)
}
}
Goroutine
マルチスレッド
package main
import (
"fmt"
"time"
)
func goroutin(s string){
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func normal(s string){
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main(){
go goroutin("go")
normal("hello")
}
package main
import (
"fmt"
"sync"
)
syncを使う場合
func goroutin(s string, wg *sync.WaitGroup){
for i := 0; i < 5; i++ {
fmt.Println(s)
}
wg.Done()
}
func normal(s string){
for i := 0; i < 5; i++ {
fmt.Println(s)
}
}
func main(){
var wg sync.WaitGroup
wg.Add(1)
go goroutin("go", &wg)
normal("hello")
wg.Wait()
}
chanel
package main
import (
"fmt"
)
func goroutin1(s []int, c chan int){
sum :=0
for _, v := range s{
sum += v
}
c <- sum
}
func goroutin2(s []int, c chan int){
sum :=0
for _, v := range s{
sum += v
}
sum = sum * 2
c <- sum
}
func normal(arr []int) int{
sum := 0
for _, a := range arr{
sum += a
}
sum = sum - 15
return sum
}
func main(){
s := []int{1, 2, 3, 4, 5}
c := make(chan int)
go goroutin1(s, c)
go goroutin2(s, c)
fmt.Println(normal(s))
x := <-c
fmt.Println(x)
y := <-c
fmt.Println(y)
}
