Packages, Modules และ Imports
Packages: ระบบโมดูลของ Go
หัวข้อที่มีชื่อว่า “Packages: ระบบโมดูลของ Go”TypeScript ใช้ ES modules (import/export) ร่วมกับ npm ในการจัดการ package ส่วน Go มีแนวคิดที่คล้ายกัน: package (ไดเรกทอรีของไฟล์ .go ที่ใช้คำประกาศ package ร่วมกัน) และ module (กลุ่มของ package ที่นิยามโดย go.mod เทียบได้กับ package.json)
Packages และคำประกาศ package
หัวข้อที่มีชื่อว่า “Packages และคำประกาศ package”ไฟล์ Go ทุกไฟล์เริ่มต้นด้วย package <name> ไฟล์ในไดเรกทอรีเดียวกันใช้ package ร่วมกัน ส่วนโปรแกรมที่รันได้ใช้ package main
// TypeScript: file is automatically a moduleexport function add(a: number, b: number): number { return a + b;}export const PI = 3.14159;// Go: explicit package declarationpackage mathutil
func Add(a, b int) int { return a + b}
const PI = 3.14159Exported เทียบกับ unexported identifiers
หัวข้อที่มีชื่อว่า “Exported เทียบกับ unexported identifiers”ระบบ export ของ Go เรียบง่ายอย่างหมดจด: ขึ้นต้นด้วยตัวพิมพ์ใหญ่ → exported (public) ขึ้นต้นด้วยตัวพิมพ์เล็ก → unexported (เป็น private ภายใน package) ไม่ต้องใช้คีย์เวิร์ด export
// TypeScript: explicit export keywordexport function PublicFunc() { ... }function privateFunc() { ... } // not exported
export class PublicClass { ... }class InternalClass { ... }// Go: capitalisation IS the export keywordfunc PublicFunc() { ... } // exported — capital Pfunc privateFunc() { ... } // unexported — lowercase p
type PublicStruct struct { ... }type internalStruct struct { ... }go.mod — สิ่งเทียบเท่ากับ package.json
หัวข้อที่มีชื่อว่า “go.mod — สิ่งเทียบเท่ากับ package.json”// package.json (npm){ "name": "my-app", "version": "1.0.0", "dependencies": { "express": "^4.18.0" }}
// Add dependency:// npm install express// go.modmodule github.com/user/my-app
go 1.22
require ( github.com/gin-gonic/gin v1.9.1)
// Add dependency:// go get github.com/gin-gonic/ginการ import package
หัวข้อที่มีชื่อว่า “การ import package”// TypeScriptimport { readFileSync } from 'fs';import express from 'express';import { add } from './mathutil';// Goimport ( "os" // stdlib "github.com/gin-gonic/gin" // third-party "github.com/user/app/mathutil" // local package)ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”package main
import ( "fmt" "strings" "unicode")
func isExported(name string) bool { if name == "" { return false } return unicode.IsUpper(rune(name[0]))}
func main() { names := []string{"Println", "printf", "HTTP", "myHelper", "PublicAPI"} for _, n := range names { status := "unexported" if isExported(n) { status = "EXPORTED" } fmt.Printf("%-12s -> %s\n", n, status) }
s := "go for typescript developers" fmt.Println(strings.ToTitle(s))}Loading Go runtime (first run only, ~8 MB)…