Documentation
¶
Overview ¶
This `magicstring` package is designed to attach arbitrary data to a Go built-in `string` type and read the data later. The string with attached data is called "magic string" here.
Example (DestroyMagicString) ¶
magicString := Attach("magic string", 123) buf := make([]byte, len(magicString)) copy(buf, magicString) ordinaryString := string(buf) detachedString := Detach(magicString) fmt.Println(Is(magicString)) fmt.Println(Is(ordinaryString)) fmt.Println(Is(detachedString))
Output: true false false
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Attach ¶
Attach associates a newly allocated string with data. The value of the returned string is guaranteed to be identical to str.
Example ¶
type T struct { Name string } s1 := "Hello, world!" data := &T{Name: "Kanon"} s2 := Attach(s1, data) attached := Read(s2).(*T) fmt.Println(s1 == s2) fmt.Println(attached == data)
Output: true true
func Detach ¶
Detach returns a new string without any attached data. If str is an ordinary string, Detach just simply returns str.
func Is ¶
Is checks if there is any data attached to str.
Example ¶
s1 := "ordinary string" s2 := Attach("magic string", 123) s3 := s2 s4 := fmt.Sprint(s2) fmt.Println(Is(s1)) fmt.Println(Is(s2)) fmt.Println(Is(s3)) fmt.Println(Is(s4))
Output: false true true false
func Read ¶
func Read(str string) interface{}
Read reads the attached data inside the str. If there is no such data, it returns nil.
func Replace ¶ added in v1.0.2
Replace replaces the attached data in str if str is a magic string. If str is an ordinary string, Replace creates a magic string with data.
Replace returns true if the data is replaced, false if not.
Example ¶
s := Attach("magic string", 123) fmt.Println(Read(s)) success := Replace(s, "replaced") fmt.Println(success) fmt.Println(Read(s))
Output: 123 true replaced
Types ¶
This section is empty.