Files
go-basics/stage06-oop/02-methods/main.go
T

164 lines
2.7 KiB
Go
Raw Normal View History

2026-03-14 19:03:12 +08:00
package main
import "fmt"
type Person struct {
Name string
Age int
Email string
}
func (p Person) GetName() string {
return ____
}
func (p Person) GetAge() int {
return ____
}
func (p *Person) SetName(name string) {
____ = ____
}
func (p *Person) SetEmail(email string) {
____ = ____
}
func (p Person) GetInfo() string {
return fmt.Sprintf("%s, %d岁, %s", ____, ____, ____)
}
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return ____
}
func (r *Rectangle) Resize(width, height float64) {
____ = ____
____ = ____
}
type BankAccount struct {
Balance float64
Owner string
}
func (b *BankAccount) Deposit(amount float64) {
b.Balance += ____
}
func (b *BankAccount) Withdraw(amount float64) bool {
if b.Balance >= amount {
b.Balance -= ____
return ____
}
return false
}
func (b BankAccount) GetBalance() float64 {
return ____
}
func exercise1() string {
fmt.Println("=== 练习1:基础方法 ===")
person := Person{Name: "张三", Age: 25, Email: "zhangsan@example.com"}
name := ____
age := ____
person.SetName(____)
person.SetEmail(____)
fmt.Printf("姓名: %s, 年龄: %d\n", ____, person.Age)
return ____
}
func exercise2() float64 {
fmt.Println("=== 练习2:矩形方法 ===")
rect := Rectangle{Width: 10, Height: 5}
area := ____
fmt.Printf("矩形面积: %.2f\n", area)
rect.Resize(____, ____)
newArea := ____
fmt.Printf("调整后面积: %.2f\n", ____)
return ____
}
func exercise3() float64 {
fmt.Println("=== 练习3:银行账户方法 ===")
account := BankAccount{Balance: 1000, Owner: "张三"}
account.____(500)
fmt.Printf("存款后余额: %.2f\n", account.____())
success := account.____(300)
if success {
fmt.Printf("取款成功,余额: %.2f\n", account.____())
}
return ____
}
func exercise4() string {
fmt.Println("=== 练习4:方法链 ===")
// 使用方法链调用
person := Person{Name: "李四", Age: 30, Email: "lisi@example.com"}
person.SetName("李四(更新)").SetEmail("lisi_new@example.com")
return ____
}
func exercise5() int {
fmt.Println("=== 练习5:计算器方法 ===")
type Calculator struct {
value int
}
calc := Calculator{value: 0}
calc.setValue := func(v int) {
calc.value = v
}
calc.setValue(10)
fmt.Printf("计算器值: %d\n", calc.value)
return ____
}
func main() {
fmt.Println("=== 方法 练习 ===\n")
result1 := exercise1()
fmt.Printf("练习1结果: %s\n", result1)
result2 := exercise2()
fmt.Printf("练习2结果: %.2f\n", result2)
result3 := exercise3()
fmt.Printf("练习3结果: %.2f\n", result3)
result4 := exercise4()
fmt.Printf("练习4结果: %s\n", result4)
result5 := exercise5()
fmt.Printf("练习5结果: %d\n", result5)
}