พื้นฐาน Go

Go Functions and Multiple Return Values

Functions in Go can return several values. Learn the result-and-error pattern and variadic parameters.

  • ระดับเริ่มต้น
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Parameters and results
  • Returning a value and an error
  • Variadic functions
divide(a, b)
divide(10, 4)2.5, nil
divide(1, 0)0, "cannot divide by zero"

A result and an error

A function groups code under a name. Go functions can return several values, and the usual pattern is to return a result together with an error.

divide returns the result and an error; nil means there was no error. The underscore ignores a value you do not need. numbers ...int accepts any number of integers, and the named result total is returned by the bare return.

ประเด็นสำคัญ

  1. A function can return more than one value.
  2. nil means there was no error.
  3. _ ignores a value you do not need.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import (
	"errors"
	"fmt"
)

func area(width, height int) int {
	return width * height
}

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return a / b, nil
}

func sum(numbers ...int) (total int) {
	for _, n := range numbers {
		total += n
	}
	return
}

func main() {
	fmt.Println(area(4, 5))

	if result, err := divide(10, 4); err == nil {
		fmt.Println(result)
	}
	_, err := divide(1, 0)
	fmt.Println(err)

	fmt.Println(sum(1, 2, 3, 4))
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
20
2.5
cannot divide by zero
10

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Fibonacci Sequence →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด