How do you trim trailing byte 0s from a string?

646 views
Skip to first unread message

Howard Guo

unread,
Aug 5, 2015, 3:07:35 AM8/5/15
to golang-nuts
Hello gophers!

String comparison does not work as expected on a string with training byte 0s, for example string([]byte{97, 0}) != "a".

So what is the most efficient way to remove training byte 0s from a string?

Thanks & regards,
Howard

Caleb Spare

unread,
Aug 5, 2015, 3:15:18 AM8/5/15
to Howard Guo, golang-nuts
You are comparing two different strings. (Go does not use null
termination for its strings.)

I'm not sure about "most efficient", but a relatively simple way is
strings.TrimRight:

http://play.golang.org/p/1H_blATQVM

Note that if your null-terminated string comes via cgo, the C.GoString
function should take care of the conversion for you.

-Caleb
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Roberto Zanotto

unread,
Aug 5, 2015, 8:29:20 AM8/5/15
to golang-nuts, guoh...@gmail.com
+1
Removing trailing zeroes is probably never gonna be a bottleneck in your application, you should go for simplicity, not efficiency :)

Howard Guo

unread,
Aug 5, 2015, 11:30:51 AM8/5/15
to Roberto Zanotto, golang-nuts
Good idea, thanks to both of you!
Reply all
Reply to author
Forward
0 new messages