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

Packages, Modules และ Imports

TypeScript ใช้ ES modules (import/export) ร่วมกับ npm ในการจัดการ package ส่วน Go มีแนวคิดที่คล้ายกัน: package (ไดเรกทอรีของไฟล์ .go ที่ใช้คำประกาศ package ร่วมกัน) และ module (กลุ่มของ package ที่นิยามโดย go.mod เทียบได้กับ package.json)

ไฟล์ Go ทุกไฟล์เริ่มต้นด้วย package <name> ไฟล์ในไดเรกทอรีเดียวกันใช้ package ร่วมกัน ส่วนโปรแกรมที่รันได้ใช้ package main

TypeScript
// TypeScript: file is automatically a module
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;
Go
// Go: explicit package declaration
package mathutil
func Add(a, b int) int {
return a + b
}
const PI = 3.14159

ระบบ export ของ Go เรียบง่ายอย่างหมดจด: ขึ้นต้นด้วยตัวพิมพ์ใหญ่ → exported (public) ขึ้นต้นด้วยตัวพิมพ์เล็ก → unexported (เป็น private ภายใน package) ไม่ต้องใช้คีย์เวิร์ด export

TypeScript
// TypeScript: explicit export keyword
export function PublicFunc() { ... }
function privateFunc() { ... } // not exported
export class PublicClass { ... }
class InternalClass { ... }
Go
// Go: capitalisation IS the export keyword
func PublicFunc() { ... } // exported — capital P
func privateFunc() { ... } // unexported — lowercase p
type PublicStruct struct { ... }
type internalStruct struct { ... }
TypeScript
// package.json (npm)
{
"name": "my-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.0"
}
}
// Add dependency:
// npm install express
Go
// go.mod
module 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
TypeScript
// TypeScript
import { readFileSync } from 'fs';
import express from 'express';
import { add } from './mathutil';
Go
// Go
import (
"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))
}
Go กำหนดว่า identifier เป็น exported (public) อย่างไร?
สิ่งเทียบเท่ากับ package.json ใน Go คืออะไร?
คำประกาศ package ใดที่โปรแกรม Go ที่รันได้ทุกตัวต้องใช้?
คำสั่งใดที่เพิ่ม dependency จากภายนอกเข้าไปใน Go module?