英文:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论