你如何解决以下的Golang挑战?

huangapple go评论73阅读模式
英文:

How would you solve the following Golang challenge?

问题

我必须解决以下的TreeHouse Go挑战,但我在Print方法中卡住了。

要求:

clockcalendar包中,我们定义了ClockCalendar类型,它们都有一个Display方法,你可以调用它们来打印它们。
schedule包中,定义一个Displayable接口,该接口满足ClockCalendar类型上的Display方法。(不要对clockcalendar包进行任何更改。)然后,在schedule包中,定义一个Print函数,该函数接受一个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()
}

huangapple
  • 本文由 发表于 2017年7月3日 20:40:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/44885848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定