ข้ามไปยังเนื้อหา

Hello, World!

ใน TypeScript/Node.js คุณสร้างไฟล์, export หรือเขียนโค้ดไว้ที่ top-level แล้ว node ก็รันให้ ส่วน Go กำหนดให้ทุกโปรแกรมที่รันได้ต้องมีโครงสร้างเฉพาะ: ประกาศ package main และมี entry point func main() มาเทียบกัน

TypeScript
// hello.ts
console.log("Hello, World!");
// รันด้วย: npx ts-node hello.ts
// หรือคอมไพล์: tsc hello.ts && node hello.js
Go
// hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
// รันด้วย: go run hello.go

package main

ทุกไฟล์ Go เริ่มด้วยการประกาศ package และ package ชื่อ main นั้นพิเศษ — เป็นตัวบอกว่านี่คือโปรแกรมที่รันได้ ไม่ใช่ library เทียบได้กับไฟล์ที่ field "main" ใน package.json ชี้ไปหา

import "fmt"

การ import ของ Go เป็นแบบ explicit และทำทีละไฟล์ fmt คือ standard library package สำหรับงาน formatted I/O — เทียบได้กับ console ในโลก Go คุณ import ด้วย full package path แบบ string (ต้องใส่ quote) และ import ที่ไม่ได้ใช้จะกลายเป็น compile error

func main()

Function main คือ entry point ทุกโปรแกรม Go ที่รันได้ต้องมี func main() เพียงตัวเดียวใน package main และไม่รับ argument ใด ๆ — ถ้าต้องการ command-line argument ให้อ่านจาก os.Args

TypeScript
// TypeScript: หลาย entry style
// 1. Top-level code (scripts)
console.log("รันทันที");
// 2. "main" ใน package.json ชี้มาที่นี่
// 3. Exported function ที่ framework เรียก
Go
// Go: entry point เดียวเสมอ
package main
import "fmt"
func main() {
// โปรแกรมเริ่มที่นี่เสมอ
fmt.Println("รันก่อน")
}

fmt.Println คือสิ่งที่ใกล้เคียง console.log ที่สุด นอกจากนี้ package fmt ยังมี fmt.Printf สำหรับ format string (เหมือน printf ใน C หรือ template literal ใน JS) และ fmt.Sprintf สำหรับสร้าง string โดยไม่ print ออกมา

TypeScript
// TypeScript logging
console.log("Hello"); // ง่ายๆ
console.log("Name:", name); // หลาย arg
console.log(`Score: ${score}`); // template literal
const msg = `Hello, ${name}!`; // สร้าง string
Go
// Go fmt package
fmt.Println("Hello") // ง่ายๆ
fmt.Println("Name:", name) // หลาย arg
fmt.Printf("Score: %d\n", score) // format verb
msg := fmt.Sprintf("Hello, %s!", name) // สร้าง string

fmt.Printf ใช้ format verb แทน template literal ตัวที่ใช้บ่อยมีดังนี้:

Verbความหมายเทียบเท่า TypeScript
%sstring${str}
%dinteger${num}
%ffloat${num.toFixed(6)}
%.2ffloat, ทศนิยม 2 ตำแหน่ง${num.toFixed(2)}
%vค่าใดๆ (รูปแบบ default)${JSON.stringify(val)}
%Tชื่อ typetypeof val
%+vstruct พร้อมชื่อ fieldJSON.stringify(val, null, 2)
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
// fmt.Printf ใช้ format verb — เหมือน template literal
name := "Gopher"
age := 3
fmt.Printf("Name: %s, Age: %d\n", name, age)
// fmt.Sprintf สร้าง string โดยไม่ print
greeting := fmt.Sprintf("Welcome, %s!", name)
fmt.Println(greeting)
}
ทุกโปรแกรม Go ที่รันได้ต้องมีอะไร?
เกิดอะไรขึ้นถ้า import package แต่ไม่ได้ใช้ใน Go?
fmt function ไหนสร้าง formatted string โดยไม่ print?
format verb ของ Go สำหรับ print integer คืออะไร?