แบบฝึกหัด Go
Temperature Converter in Go
Give Celsius and Fahrenheit their own types so the compiler stops you mixing them.
สิ่งที่คุณจะได้เรียนรู้
- Defined types
- Methods on number types
- The String method
convert
100.0°C212.0°F98.6°F37.0°C-40.0°C-40.0°FThe unit is part of the type
Giving each unit its own type lets the compiler stop you from mixing Celsius and Fahrenheit by accident, even though both are float64 underneath.
Celsius and Fahrenheit are separate types with their own methods. A String method decides how fmt.Println prints a value, here with one digit after the decimal point. -40 is the one temperature that is the same on both scales.
ประเด็นสำคัญ
- Celsius and Fahrenheit are separate types.
- A String method controls printing.
- -40 is the same on both scales.
ตัวอย่าง Go ที่รันได้
main.go
package main
import "fmt"
type Celsius float64
type Fahrenheit float64
func (c Celsius) ToFahrenheit() Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func (f Fahrenheit) ToCelsius() Celsius { return Celsius((f - 32) * 5 / 9) }
func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%.1f°F", float64(f)) }
func main() {
boiling := Celsius(100)
body := Fahrenheit(98.6)
cold := Celsius(-40)
fmt.Println(boiling, "=", boiling.ToFahrenheit())
fmt.Println(body, "=", body.ToCelsius())
fmt.Println(cold, "=", cold.ToFahrenheit())
}
100.0°C = 212.0°F
98.6°F = 37.0°C
-40.0°C = -40.0°Fฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด