package main import ( "fmt" "go.wit.com/lib/protobuf/chatpb" "google.golang.org/protobuf/proto" ) func main() { // 1. Create our source object that we want to copy. originalChat := &chatpb.Chat{ From: chatpb.Who_USER, Content: "This is a test message.", Uuid: "uuid-original", } // 2. Create the list we want to append to. allChats := &chatpb.Chats{ Uuid: "main-chat-list", } fmt.Printf("Before copy, originalChat's content: '%s'\n", originalChat.GetContent()) fmt.Printf("Initial length of allChats: %d\n\n", len(allChats.GetChats())) // 3. Create a deep copy using proto.Clone(). // The result is a proto.Message, so we must type-assert it back to *chatpb.Chat. chatCopy := proto.Clone(originalChat).(*chatpb.Chat) // 4. Append the COPY to the list. allChats.Chats = append(allChats.GetChats(), chatCopy) fmt.Println("--- Appended the copy. Now modifying the original... ---") // 5. Now, modify the original object. originalChat.Content = "The original message has been changed!" originalChat.Uuid = "uuid-modified" // 6. Prove that the copy in the list was NOT affected. fmt.Printf("\nAfter modification, originalChat's content: '%s'\n", originalChat.GetContent()) appendedChat := allChats.GetChats()[0] fmt.Printf("Appended chat's content: '%s'\n", appendedChat.GetContent()) fmt.Printf("Appended chat's UUID: '%s'\n", appendedChat.GetUuid()) fmt.Println("\nSuccess! The appended chat is an independent copy and was not affected by changes to the original.") }