Open11
Goに手をだす


helixはlsp関連の連携が優秀なのでbrewでgoとか入ってれば普通に動く

init project
mkdir hello
cd hello
go mod init example/hello

cargo new
と違ってmain.go的なファイルは作成されないので作成。
touch main.go
以下を貼り付け

main.go
package main
import "fmt"
func main() {
fmt.Println("hello world!!!")
}

実行
go run .
hello world!!!

数あてゲーム 動く方 -> https://zenn.dev/link/comments/556172cc3c67e3
main.go
package main
import (
"cmp"
"fmt"
"strconv"
)
import "math/rand"
func main() {
fmt.Println("Guess the number!")
secret_number := rand.Intn(101)
for {
fmt.Println("Please input your guess.")
var input string
fmt.Scan(input)
guess, err := strconv.Atoi(input)
if err != nil {
panic(err)
}
fmt.Println("you guessed: ", guess)
res := cmp.Compare(guess, secret_number)
switch res {
case -1:
fmt.Println("Too small!")
case 0:
fmt.Println("You win!")
default:
fmt.Println("Too Big!")
}
}
}

を参考に

でもエラーに(numberのスペルミスは無視して)
❯ go run .
Guess the numver!
Please input your guess.
panic: strconv.Atoi: parsing "": invalid syntax

- 入力を"bufio"に変更
- winの場合にloopする問題をラベルで解決
main.go
package main
import (
"bufio"
"cmp"
"fmt"
"os"
"strconv"
)
import "math/rand"
func main() {
fmt.Println("Guess the number!")
secret_number := rand.Intn(101)
loop:
for {
fmt.Println("Please input your guess.")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
guess, err := strconv.Atoi(input)
if err != nil {
panic(err)
}
fmt.Println("you guessed: ", guess)
res := cmp.Compare(guess, secret_number)
switch res {
case -1:
fmt.Println("Too small!")
case 0:
fmt.Println("You win!")
break loop
default:
fmt.Println("Too Big!")
}
}
}

印象
- インデントがtab
- 表示媒体によって結構変わるのが気に入らない
- エラーハンドリングがやりにくい
- なんかもっといい方法はありそう
- 省略記法として
:=
は面白いけど選択肢が増えるので好きじゃない - モダンなC?
- 式指向でないのでいろんなものが値を返さない