英文:
How would you solve the following Golang challenge?
问题
我必须解决以下的TreeHouse Go挑战,但我在Print方法中卡住了。
要求:
在
clock和calendar包中,我们定义了Clock和Calendar类型,它们都有一个Display方法,你可以调用它们来打印它们。
在schedule包中,定义一个Displayable接口,该接口满足Clock和Calendar类型上的Display方法。(不要对clock或calendar包进行任何更改。)然后,在schedule包中,定义一个Displayable值并调用其上的Display方法。
clock.go:
package clock
import "fmt"
type Clock struct {
Hours int
Minutes int
}
func (c Clock) Display() {
fmt.Printf("%02d:%02d", c.Hours, c.Minutes)
}
calendar.go:
package calendar
import "fmt"
type Calendar struct {
Year int
Month int
Day int
}
func (c Calendar) Display() {
fmt.Printf("%04d-%02d-%02d", c.Year, c.Month, c.Day)
}
schedule.go:
package schedule
// 在这里声明一个Displayable接口
type Displayable interface {
Display()
}
// 在这里声明一个Print函数(我在这里卡住了)
谢谢!
英文:
I have to solve following TreeHouse Go challenge, but I'm stuck in the Print method.
The requirement:
> In the clock and calendar packages, we've defined Clock and Calendar types, both of which have a Display method that you can call to print them.
In the schedule package, define a Displayable interface that is satisfied by the Display methods on both the Clock and Calendar types. (Don't make any changes to the clock or calendar packages.) Then, still in the schedule package, define a Print function that takes a Displayable value and calls Display on it.
clock.go:
package clock
import "fmt"
type Clock struct {
Hours int
Minutes int
}
func (c Clock) Display() {
fmt.Printf("%02d:%02d", c.Hours, c.Minutes)
}
calendar.go:
package calendar
import "fmt"
type Calendar struct {
Year int
Month int
Day int
}
func (c Calendar) Display() {
fmt.Printf("%04d-%02d-%02d", c.Year, c.Month, c.Day)
}
schedule.go:
package schedule
// DECLARE A Displayable INTERFACE HERE
type Displayable interface {
Display()
}
// DECLARE A Print FUNCTION HERE (I'm stuck here)
Thank you!
答案1
得分: 2
func Print(d Displayable) {
d.Display()
}
英文:
func Print(d Displayable) {
d.Display()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论