我試圖在 Go 中復制一個結構體,但在這方面找不到很多資源。這是我所擁有的:type Server struct { HTTPRoot string // Location of the current subdirectory StaticRoot string // Folder containing static files for all domains Auth Auth FormRecipients []string Router *httprouter.Router}func (s *Server) Copy() (c *Server) { c.HTTPRoot = s.HTTPRoot c.StaticRoot = s.StaticRoot c.Auth = s.Auth c.FormRecipients = s.FormRecipients c.Router = s.Router return}第一個問題,這不會是深拷貝,因為我不是在拷貝 s.Auth。這至少是一個正確的淺拷貝嗎?第二個問題,是否有更慣用的方式來執(zhí)行深(或淺)復制?編輯:我玩過的另一種選擇非常簡單,它使用了參數(shù)按值傳遞的事實。func (s *Server) Copy() (s2 *Server) { tmp := s s2 = &tmp return}這個版本好點了嗎?(這是正確的嗎?)
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
作業(yè)是副本。你的第二個函數(shù)很接近,你只需要取消引用s
.
這將復制*Server
s
到c
c := new(Server) *c = *s
至于深拷貝,則需要遍歷字段,并確定需要遞歸復制的內容。*httprouter.Router
如果它包含未導出字段中的數(shù)據(jù),則取決于是什么,您可能無法進行深層復制。
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消