Go Lang Install

Summary: Author: 张亚飞 | Read Time: 1 minute read | Published: 2018-03-30
Filed under Categories: LinuxTags: Note,

Go 坑

type Question struct {
	ID      int
	Content string
	Answers map[int]string
}

func NewQuestion(id int, content string) Question {
	return Question{
		ID:      id,
		Content: content,
		Answers: make(map[int]string),
	}
}

func (q Question) AddAnswer(id int, content string) Question {
	q.Answers[id] = content
	return q
}

func (q Question) ShowAnswers() {
	for _, answer := range q.Answers {
		fmt.Printf("* %s\n", answer)
	}
}

以下代码输出什么结果

q1 := NewQuestion(1, "How to be cool?")
q1 = q1.AddAnswer(1, "eat peanuts")

q2 := q1

q2 = q2.AddAnswer(2, "visit developer20.com regulary!")
fmt.Println("How to be cool?")
q1.ShowAnswers()

答案是

How to be cool?
 * eat peanuts
 * visit developer20.com regulary!

Be aware of copying in Go

Comments

Cor-Ethan, the beverage → www.iirii.com