我有下面的代码,它的目的只是创建结构对象的映射,并调用一个复制映射然后打印它的函数。当我删除所有内容中的行时,一切都有效(除了id,它对于每次运行都是常数,正如预期的那样),否则它只会将最后一个元素添加到映射中。为什么会发生这种情况?ComicBookrand.Seed()SetId()
comicBook.go
package src
import (
"math/rand"
"sync"
"time"
)
type ComicBook struct {
id int
name string
publisher string
sold bool
}
type Book interface {
GetId() int
SetId() int
GetName() string
GetPublisher() string
GetIsSold() bool
New(name string, author string) ComicBook
}
func (book ComicBook) SetId() int{
rand.Seed(time.Now().UTC().UnixNano())
id := rand.Intn(100)
book.id = id
return id
}
func (book ComicBook) New(name string, author string) ComicBook {
id := book.SetId()
b := ComicBook{id, name, author, false}
return b
}
func (book ComicBook) GetId() int{
return book.id
}
func (book ComicBook) GetName() string{
return book.name
}
func (book ComicBook) GetPublisher() string{
return book.publisher
}
func (book ComicBook) GetIsSold() bool{
return book.sold
}
main.go
package main
import (
"awesomeProject1/src"
"fmt"
)
var (
ComicBook src.ComicBook
)
func copyMap(m map[int]src.ComicBook) map[int]src.ComicBook {
newMap := make(map[int]src.ComicBook)
for k, v := range m {
newMap[k] = v
}
return newMap
}
func main() {
b := src.ComicBook{}.New("A", "B")
bTwo := src.ComicBook{}.New("The Dark Knight Returns", "DC Comics")
bThree := src.ComicBook{}.New("Watchmen", "DC Comics")
m := map[int]src.ComicBook{
b.GetId(): b,
bTwo.GetId(): bTwo,
bThree.GetId(): bThree,
}
newMap := copyMap(m)
for k, v := range newMap {
fmt.Println("Id: ", k, ", Name: ", v.GetName(), ", Publisher: ", v.GetPublisher(), ", Sold: ", v.GetIsSold())
}
}
输出:
Id: 91 , Name: Watchmen , Publisher: DC Comics , Sold: false
茅侃侃
犯罪嫌疑人X
相关分类