Go触ってみる

Go言語触ってみる

Go言語ってなんや

Goのイメージ早いバックエンド

ISUCONでよく使われてるイメージ

話題の言語気になる

環境構築

apt

$ sudo apt install -y golang-go
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  bzip2 cpp cpp-11 fontconfig-config fonts-dejavu-core g++ g++-11 gcc gcc-11 gcc-11-base golang-1.18-go
...
Processing triggers for libc-bin (2.35-0ubuntu3.6) ...
/sbin/ldconfig.real: /usr/lib/wsl/lib/libcuda.so.1 is not a symbolic link

無事完了!らくちん

$ go version
go version go1.18.1 linux/amd64

ヨシッ

参考:Download and install - The Go Programming Languageは参考していない

hello world

go tutorialで検索して動かしてみる

出てきたコードをコピペして go run .

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
$ go run .
go: go.mod file not found in current directory or any parent directory; see 'go help modules'

なるほどねー???

go.modがないよと怒られているらしい

解決!

何も考えず go mod init する

$ go mod init example/hello
go: creating new go.mod: module example/hello
go: to add module requirements and sums:
        go mod tidy

$ go run .
Hello, World!

動いたー

所感

pythonとcみたいな感じかな?知らんけど

c味が強い気がする

参考:Tutorial: Get started with Go - The Go Programming Language

tutorial2

いわれるがままやる

コピペして

package main

import "fmt"

import "rsc.io/quote"

func main() {
    fmt.Println(quote.Go())
}
$ go mod tidy
go: finding module for package rsc.io/quote
go: downloading rsc.io/quote v1.5.2
go: found rsc.io/quote in rsc.io/quote v1.5.2
go: downloading rsc.io/sampler v1.3.0
go: downloading golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c

ファ

不足していたり、使われていないモジュールにいい感じに対応してくれるコマンドみたい、、、 便利すぎる、、、 go mod init いらないやん

$ go run .
Don't communicate by sharing memory, share memory by communicating.

参考:Tutorial: Get started with Go - The Go Programming Language

モジュールを作成、呼び出す

作成

いわれるがまま

$ mkdir greetings
$ cd greetings
$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings

ヨシッ

// greetings.go
package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

呼び出し

$ cd ..
$ mkdir hello
$ cd hello
<home>/
 |-- greetings/
 |   |-- greetings.go
 |-- hello/
		 |-- hello.go
# hello/
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello
// hello.go
package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

今の状況

<home>/
 |-- greetings/
 |   |-- go.mod
 |   |-- greetings.go
 |-- hello/
     |-- go.mod
		 |-- hello.go

mod editを使ってモジュールの場所を変更してみる

$ go mod edit -replace example.com/greetings=../greetings

すごいやつ

$ go mod tidy
$ go run .

うごいたー

するする進むなんてすばらしいチュートリアルなんだ、、、

エラー返却

さっきのにエラー処理を追加する

// hello.go
package main

import (
    "fmt"
	"log"

    "example.com/greetings"
)

func main() {
    // Set properties of the predefined Logger, including
    // the log entry prefix and a flag to disable printing
    // the time, source file, and line number.
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    // Request a greeting message.
    message, err := greetings.Hello("")
    // If an error was returned, print it to the console and
    // exit the program.
    if err != nil {
				log.Fatal(err)
    }

    // If no error was returned, print the returned message
    // to the console.
    fmt.Println(message)
}
// greetings.go
package greetings

import (
    "errors"
    "fmt"
)

// Hello returns a greeting for the named person.
//         ↓変数名 ↓型       ↓ returnの型指定
func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
		    //     ↓ ここにname ↓ ここにerror
        return "", errors.New("empty name")
    }
    // Return a greeting that embeds the name in a message.
// var message string
// message = fmt.Sprintf("Hi, %v. Welcome!", name)
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    //     ↓ name
    ↓ error
    return message, nil
}
root@ubuntu-23:~/go-tutorial/greetings/hello# go run .
greetings: empty name
exit status 1

まあわかった

math/rand

rand.Intn(3)

0~2のランダムな数字を返す

よくあるランダム関数と一緒

参考Return a random greeting - The Go Programming Language

複数人分の返信挨拶

複数の人の挨拶を返す - Go プログラミング言語

test

。。。

感想

公式チュートリアルがクッソわかりやすくてありがたい

← Go home