2 回答
TA贡献1802条经验 获得超10个赞
创建电影片段。 将每部电影附加到切片。要打印,请覆盖切片并打印每部电影。
var movies []*movie
movies = append(movies, &movie{"LOTR", "action", 120, 1999})
movies = append(movies, &movie{"Avanger", "action", 120, 2004})
movies = append(movies, &movie{"Spiderman", "action", 120, 2004})
movies = append(movies, &movie{"Juon", "horror", 120, 2004})
for i, m := range movies {
fmt.Printf("%d. Title: %s\n Genre: %s\n Duration: %d\n Year: %d\n\n", i+1, m.title, m.genre, m.duration, m.year)
}
逻辑可以包含在一个类型中:
// dataFilms stores data for multiple films.
type dataFilms []*movie
func (df *dataFilms) add(title string, genre string, duration int, year int) {
*df = append(*df, &movie{title, genre, duration, year})
}
func (df dataFilms) print() {
for i, m := range df {
fmt.Printf("%d. Title: %s\n Genre: %s\n Duration: %d\n Year: %d\n\n", i+1, m.title, m.genre, m.duration, m.year)
}
}
func main() {
var df dataFilms
df.add("LOTR", "action", 120, 1999)
df.add("Avanger", "action", 120, 2004)
df.add("Spiderman", "action", 120, 2004)
df.add("Juon", "horror", 120, 2004)
df.print()
}
TA贡献1712条经验 获得超3个赞
创建结构新的电影数组
创建全局变量 Movies 来保存数据
在 func main 上调用变量
type Movie struct {
Title string
Genre string
Duration int
Year int
}
type Movies []Movie
var dest Movies
func addDataFilm(title string, genre string, duration int, year int) Movies {
dest = append(dest, Movie{
Title: title,
Genre: genre,
Duration: duration,
Year: year,
})
return dest
}
func TestNumberToAlphabet(t *testing.T) {
addDataFilm("LOTR", "action", 120, 1999)
addDataFilm("Avanger", "action", 120, 2004)
addDataFilm("Spiderman", "action", 120, 2004)
addDataFilm("Juon", "horror", 120, 2004)
fmt.Println(dest)
}
- 2 回答
- 0 关注
- 152 浏览
添加回答
举报