- 将struct定义为一种类型Car
- NewCar函数return &Car{},返回指针
// car.go
package elon
// Car implements a remote controlled car.
type Car struct {
speed int
batteryDrain int
battery int
distance int
}
// NewCar creates a new car with given specifications.
func NewCar(speed, batteryDrain int) *Car {
return &Car{
speed: speed,
batteryDrain: batteryDrain,
battery: 100,
}
}
- 给Car类型绑定方法
- 绑定方法到*Car,说明在指针上,函数内可以改变结构体的值;如果是Car,则是拷贝,不能改变原始变量的值。
- 给新的自定义类型绑定方法不一定要求类型是struct,也可以是int等一般类型。
package elon
import "fmt"
// TODO: define the 'Drive()' method
func (car *Car) Drive() {
if car.battery < car.batteryDrain {
return
}
car.distance += car.speed
car.battery -= car.batteryDrain
}
// TODO: define the 'DisplayDistance() string' method
func (car *Car) DisplayDistance() string {
return fmt.Sprintf("Driven %d meters", car.distance)
}
// TODO: define the 'DisplayBattery() string' method
func (car *Car) DisplayBattery() string {
return fmt.Sprintf("Battery at %d%%", car.battery)
}
// TODO: define the 'CanFinish(trackDistance int) bool' method
func (car *Car) CanFinish(trackDistance int) bool {
if (trackDistance+car.speed-1)/car.speed*car.batteryDrain > car.battery {
return false
} else {
return true
}
}
标签:return,Methods,int,car,batteryDrain,Golang,Car,speed,Structs
From: https://www.cnblogs.com/roadwide/p/17134853.html