คุณเคยรู้สึกเบื่อหน่ายกับการพิมพ์ if err != nil ซ้ำแล้วซ้ำอีกใน Go หรือไม่? หรือเคยอยากมี Pattern Matching และ Sum Types เหมือนใน Rust? Dingo คือคำตอบที่คุณกำลังมองหา
Dingo คืออะไร?
Dingo เป็น meta-language สำหรับ Go ที่คล้ายกับความสัมพันธ์ระหว่าง TypeScript กับ JavaScript โดย Dingo จะทำหน้าที่เป็นภาษาที่มีฟีเจอร์สมัยใหม่มากกว่า แต่ในท้ายที่สุดจะถูก transpile (แปลง) เป็นโค้ด Go ที่สะอาดและอ่านง่าย
จุดเด่นของ Dingo
- Result Types สำหรับการจัดการ error อย่างมีระบบ
- Pattern Matching แทน switch statement ธรรมดา
- Error Propagation (?) ลด boilerplate code
- Sum Types ที่ชาว Go ร้องขอมานาน
- Zero runtime overhead เพราะกลายเป็น Go code ในที่สุด
ที่สำคัญ Dingo ไม่ได้เป็น runtime ใหม่หรือ ecosystem ใหม่ มันคือ syntax ที่ดีกว่าที่แปลงกลายเป็น Go code ปกติ ทำให้คุณสามารถใช้ library ใดๆ ของ Go ได้อย่างสมบูรณ์
การติดตั้ง
การติดตั้ง Dingo ทำได้ง่ายๆ เพียงแค่ clone repository และ build compiler:
# Clone repository
git clone https://github.com/MadAppGang/dingo.git
cd dingo
# Build compiler
go build -o dingo ./cmd/dingo
# เพิ่ม dingo ไปยัง PATH (optional)
export PATH=$PATH:$(pwd)หลังจากติดตั้งเสร็จแล้ว คุณสามารถตรวจสอบได้โดยรันคำสั่ง:
dingo --versionการใช้งาน
โปรแกรมแรกของคุณ
สร้างไฟล์ hello.dingo:
package main
import "fmt"
func main() {
let message = "สวัสดีจาก Dingo!"
fmt.Println(message)
}รันโปรแกรม:
# Transpile และรันในคำสั่งเดียว
dingo run hello.dingo
# หรือ transpile ก่อนแล้วค่อยรัน
dingo build hello.dingo
go run hello.goSum Types และ Pattern Matching
นี่คือฟีเจอร์ที่โดดเด่นที่สุดของ Dingo - การใช้ Sum Types กับ Pattern Matching:
enum Result {
Ok(value: int),
Error(message: string)
}
func divide(a: int, b: int) Result {
if b == 0 {
return Error("หารด้วยศูนย์ไม่ได้")
}
return Ok(a / b)
}
func main() {
let result = divide(10, 2)
match result {
Ok(value) => fmt.Printf("ผลลัพธ์: %d\n", value),
Error(msg) => fmt.Printf("เกิดข้อผิดพลาด: %s\n", msg)
}
}Error Propagation ด้วย Operator ?
Operator ? ช่วยให้คุณจัดการ error ได้สะดวกขึ้นมาก:
func processOrder(orderID: string) -> Result<Order, Error> {
let order = fetchOrder(orderID)? // ถ้า error จะ return ทันที
let validated = validateOrder(order)? // ไม่ต้องเขียน if err != nil
let payment = processPayment(validated)?
return Ok(payment)
}Sum Types คืออะไร?
Sum Types (หรือ Algebraic Data Types) คือระบบ type ที่ให้คุณสร้าง type ที่มีได้หลายรูปแบบ (variants) โดยแต่ละรูปแบบสามารถมีข้อมูลที่แตกต่างกันได้ เหมาะสำหรับจำลองสถานการณ์ที่มีหลายความเป็นไปได้
ข้อดีของ Sum Types
- Type-safe - compiler บังคับให้จัดการทุกกรณี
- ชัดเจน - แสดงความเป็นไปได้ทั้งหมดผ่าน type definition
- ลด bugs - ไม่มีกรณีที่ลืมจัดการ
ตัวอย่าง 1: การจัดการสถานะการชำระเงิน
// กำหนด Sum Type สำหรับสถานะการชำระเงิน
enum PaymentStatus {
Pending, // รอการชำระ
Processing{transactionId: string}, // กำลังประมวลผล
Success{
transactionId: string,
amount: float64,
timestamp: time.Time
},
Failed{
reason: string,
retryable: bool
}
}
// ใช้งานกับ Pattern Matching
func handlePaymentResult(status: PaymentStatus) {
match status {
Pending => {
println("รอการชำระเงิน...")
showWaitingScreen()
},
Processing{transactionId} => {
println("กำลังประมวลผล: " + transactionId)
showLoadingIndicator()
},
Success{transactionId, amount, timestamp} => {
println("ชำระเงินสำเร็จ!")
sendReceipt(transactionId, amount)
logTransaction(timestamp)
},
Failed{reason, retryable} => {
println("ชำระเงินล้มเหลว: " + reason)
if retryable {
showRetryButton()
} else {
showContactSupport()
}
}
}
}ตัวอย่าง 2: API Response
// Sum Type สำหรับ API Response
enum ApiResponse<T> {
Loading,
Success(data: T),
Error{
code: int,
message: string,
retryAfter: ?int // optional
},
Unauthorized
}
// ใช้งานจริง
func displayUserProfile(response: ApiResponse<User>) {
match response {
Loading =>
showLoadingSkeleton(),
Success(user) => {
// มั่นใจได้ว่ามี user data
renderProfile(user.name, user.email)
loadUserPosts(user.id)
},
Error{code, message, retryAfter} => {
showErrorMessage(message)
if retryAfter != nil {
scheduleRetry(retryAfter)
}
logError(code, message)
},
Unauthorized => {
redirectToLogin()
clearAuthToken()
}
}
}เปรียบเทียบกับ Go
ใน Go ปกติ คุณต้องใช้ interface{} หรือ struct + constant ซึ่ง:
- ไม่มีการบังคับให้จัดการทุกกรณี (no exhaustiveness checking)
- ต้อง type assertion และ error checking ด้วยตัวเอง
- เสี่ยงต่อ runtime panic
เปรียบเทียบ Dingo กับ Go
ข้อดีของ Dingo
- +Result Types ทำให้จัดการ error ได้ดีกว่า
- +Pattern Matching ทรงพลังกว่า switch
- +ลด Boilerplate Code ด้วย ? operator
- +Sum Types ที่รอมานาน
- +Safe Navigation (?., ??)
- +Zero Runtime Overhead
- +ใช้ร่วมกับ Go ecosystem ได้ 100%
ข้อเสียของ Dingo
- -ยังไม่พร้อม Production (อยู่ในช่วงพัฒนา)
- -Community เล็ก เมื่อเทียบกับ Go
- -ต้อง Transpile ก่อนใช้งาน
- -Learning Curve สำหรับทีมที่คุ้นเคยกับ Go
- -IDE Support ยังไม่สมบูรณ์ (กำลังพัฒนา)
ข้อดีของ Go
- +Stable และ Mature
- +Community ใหญ่ และ library มากมาย
- +Simple และเรียนรู้ง่าย
- +เอกสารครบถ้วน
- +IDE Support ยอดเย่ยม
- +ได้รับการสนับสนุนจาก Google
ข้อเสียของ Go
- -ไม่มี Sum Types แม้จะถูกร้องขอมานาน
- -Error Handling ซ้ำซาก (if err != nil)
- -ไม่มี Pattern Matching
- -Nil Pointer Panic ยังเกิดได้ง่าย
- -ขาด Modern Language Features
ตัวอย่างโค้ดเปรียบเทียบ
Error Handling
func processOrder(
orderID string
) (*Order, error) {
order, err := fetchOrder(orderID)
if err != nil {
return nil, fmt.Errorf(
"fetch failed: %w", err
)
}
validated, err := validateOrder(order)
if err != nil {
return nil, fmt.Errorf(
"validation failed: %w", err
)
}
payment, err := processPayment(
validated
)
if err != nil {
return nil, fmt.Errorf(
"payment failed: %w", err
)
}
return payment, nil
}75% ของโค้ดเป็น error handling
func processOrder(
orderID: string
) -> Result<Order, Error> {
let order = fetchOrder(orderID)?
let validated = validateOrder(order)?
let payment = processPayment(
validated
)?
return Ok(payment)
}สั้นกว่า 60% แต่ปลอดภัยเท่าเดิม
Pattern Matching vs Switch
type Response struct {
Status string
Body string
Code int
}
func handle(resp Response) string {
switch resp.Status {
case "ok":
return "Success: " + resp.Body
case "not_found":
return "404: Not found"
case "error":
return fmt.Sprintf(
"Error %d", resp.Code
)
default:
return "Unknown"
}
}enum Response {
Ok(body: string),
NotFound,
Error{code: int, msg: string}
}
func handle(resp: Response) string {
match resp {
Ok(body) =>
"Success: " + body,
NotFound =>
"404: Not found",
Error{code, msg} =>
"Error " + code
}
}
ตัวอย่างจริงจาก HTTP Handler
มาดูตัวอย่างโค้ดจริงจาก HTTP API handler ที่มี error handling หลายจุด:
func (h Handler) GetUserProfile(
ctx server.Context
) {
userId, err := getUserId(ctx)
if err != nil {
log.Error(ctx.TraceID(),
fmt.Errorf("get user failed: %w", err))
ctx.AbortWithStatusJSON(
http.StatusBadRequest, nil
)
return
}
action, err := h.service.CheckRequiredAction(
ctx, userId
)
if err != nil {
log.Error(ctx.TraceID(),
fmt.Errorf("check action failed: %w", err))
ctx.AbortWithStatusJSON(
http.StatusInternalServerError, nil
)
return
}
if action != models.NoAction {
ctx.AbortWithStatusJSON(
http.StatusBadRequest,
models.RequiredActionRes{Code: action}
)
return
}
profile, err := h.service.GetProfile(
ctx, ctx.TraceID(), userId
)
if err != nil {
ctx.AbortWithStatusJSON(
http.StatusInternalServerError, nil
)
return
}
res := h.service.MaskSensitiveData(profile)
ctx.JSON(http.StatusOK, res)
}มี error handling ซ้ำซากถึง 4 จุด
func (h Handler) GetUserProfile(
ctx: server.Context
) {
let userId = getUserId(ctx)?
let action = h.service.CheckRequiredAction(
ctx, userId
)?
if action != models.NoAction {
ctx.AbortWithStatusJSON(
http.StatusBadRequest,
models.RequiredActionRes{Code: action}
)
return
}
let profile = h.service.GetProfile(
ctx, ctx.TraceID(), userId
)?
let res = h.service.MaskSensitiveData(profile)
ctx.JSON(http.StatusOK, res)
}ลด error handling ได้มากด้วย ? operator
ข้อสังเกต
- •ใช้
?operator ทำให้ ไม่ต้องเขียน if err != nil ซ้ำๆ ถึง 4 จุด - •โค้ด สั้นลงกว่า 50% แต่ยังคงความปลอดภัยเท่าเดิม
- •อ่านง่ายขึ้น เพราะ business logic ไม่ถูกกลบด้วย error handling boilerplate
สรุป
Dingo เป็นตัวเลือกที่น่าสนใจสำหรับนักพัฒนาที่รัก Go แต่ต้องการฟีเจอร์สมัยใหม่เพิ่มเติม อย่างไรก็ตาม ในขณะนี้ Dingo ยังอยู่ในช่วงพัฒนาและยังไม่พร้อมสำหรับการใช้งานจริง
คำแนะนำ
- →สำหรับการทดลอง: ลองใช้ Dingo ได้เลย มันสนุกและให้ประสบการณ์ที่ดี
- →สำหรับ Production: รอจนกว่าจะถึง v1.0 (ประมาณ 10-12 เดือน)
- →ติดตามพัฒนาการ: Star repository ใน GitHub และติดตาม releases
