DEV Community

Pallat Anchaleechamaikorn
Pallat Anchaleechamaikorn

Posted on • Edited on

7

install go

#go

ขั้นตอนการติดตั้งเพื่อเขียนภาษา go อ้างอิงตาม version ปัจจุบันที่เขียน blog นี้คือ version 1.17.3

ขั้นตอนแรก Download และติดตั้งภาษา go

https://golang.org/dl/

คำแนะนำ สำหรับคนที่ใช้ Macbook ผมแนะนำส่วนตัวว่าให้ติดตั้งแบบใช้ tar.gz แล้ว extract ไปวางไว้ที่ไหนก็ได้ ยกเว้น ~/go ยกตัวอย่างเช่น ~/sdk/go เป็นต้น จากนั้นให้เพิ่ม env GOROOT=~/sdk/go และเพิ่ม $GOROOT/bin เข้าไปใน $PATH ก็พอ

ตัวอย่างคำสั่ง

export GOROOT=~/sdk/go
export GOPATH=~/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOROOT/bin:$GOBIN
Enter fullscreen mode Exit fullscreen mode

ซึ่งสามารถนำคำสั่งเหล่านี้ไปเพิ่มไว้ใน ~/.profile หรือ ~/.zshrc หรือตามแต่ว่าจะใช้ shell ตัวไหนได้เลย

ทดสอบการติดตั้ง

สามารถทดสอบเราทำการติดตั้งสำเร็จได้ด้วยคำสั่งเหล่านี้

go version
go version go1.17.3 darwin/amd64
Enter fullscreen mode Exit fullscreen mode

ขั้นนตอนต่อมา เมื่อต้องการเขียนโปรแกรม เราสามารถไปเขียนที่ไหนก็ได้ ยกตัวอย่างเช่น

[linux/darwin]

~/projects/go/hello

[windows]

c:\projects\go\hello

เริ่มสร้าง module
คำสั่ง go mod init [module name] ตัวอย่างเช่น

go mod init hello
หรือ
go mod init github.com/myname/hello

จากนั้นสร้างไฟล์ main.go แล้วเริ่มเขียนโค้ดได้เลย

package main

func main() {
    fmt.Println("Hello, world")
}
Enter fullscreen mode Exit fullscreen mode

วิธีรัน

go run main.go

เพียงเท่านี้ก็สามารถเขียนภาษา go ได้แล้ว

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs