feat: Add Go example for correctly copying protobuf messages
- Demonstrates the use of 'proto.Clone()' to create a deep copy of a protobuf message before appending it to a slice. - Contrasts this with the incorrect method of appending a pointer, which leads to unintended shared state.
This commit is contained in:
parent
83d59c4095
commit
c9255ec0f1
|
@ -0,0 +1,47 @@
|
||||||
|
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.")
|
||||||
|
}
|
Loading…
Reference in New Issue