I want to join the text representation of a net.Addr
, and a []rune
using ": "
, resulting in a new []rune
. What's the most idiomatic way to do this?
I currently have (whitespace and explicit typing for purposes of example):
var (
netAddr net.Addr
someRunes []rune
_ []rune = append(
append(
[]rune(netAddr.String()),
[]rune(": ")...),
someRunes...
)
)
[]rune(netAddr.String()+": ")
Be clear and consise first, optimize later if there's a problem.
If you just want your code to be clear and understandable, do something like this:
[]rune(netAddr.String() + ": " + string(someRunes))
This is inefficient since there some unnecessary copies in there, but it conveys the logic in a way a human can read easily. If your profiler later tells you this is a bottleneck, your multiple append solution may still do more copies/allocations than necessary. I would do something like:
sep := []rune(": ")
addr := []rune(netAddr.String())
newRuneSlice = make([]rune, 0, len(addr) + len(sep) + len(someRunes))
newRuneSlice = append(newRuneSlice, addr...)
newRuneSlice = append(newRuneSlice, sep...)
newRuneSlice = append(newRuneSlice, someRunes...)
My guess is that your profiler won't tell you this is a bottleneck so the one liner is most likely best. However, you should be aware that the one liner only works with valid unicode. If you have invalid code points or surrogate pairs (as of Go 1.1) in your rune slice, you will end up with error runes replacing them. For most cases, this isn't a problem but it is worth thinking about.
Example: http://play.golang.org/p/AFoBX_2Wem
invalid := utf8.MaxRune + 1
fmt.Println([]rune(string(invalid))[0] == utf8.RuneError) // prints true