How to append a character to a string??

30,791 views
Skip to first unread message

perf...@gmail.com

unread,
May 11, 2012, 12:47:32 PM5/11/12
to golan...@googlegroups.com
Just a simple thing and I can't find how to do it anywhere, the append function doesn't work with strings, it says "first argument to append must be slice; have string".
Please show me some reference about strings and characters, I can't find anything in go tour and also in the spec, I can't find it in the package ref either :(.
p.s: I'm struggling to do this utter simple stupid task! I'm looking like an idiot T_T.

Miek Gieben

unread,
May 11, 2012, 3:03:03 PM5/11/12
to golan...@googlegroups.com
[ Quoting <perf...@gmail.com> in "[go-nuts] How to append a character..." ]
> Please show me some reference about strings and characters, I can't find
> anything in go tour and also in the spec, I can't find it in the package ref

Use +

str := str + "a"

for instance.


Regards,

--
Miek Gieben http://miek.nl
signature.asc

Jan Mercl

unread,
May 11, 2012, 3:03:41 PM5/11/12
to perf...@gmail.com, golan...@googlegroups.com

"Strings can be concatenated using the + operator or the += assignment operator"

Patrick Mylund Nielsen

unread,
May 11, 2012, 3:53:42 PM5/11/12
to perf...@gmail.com, Jan Mercl, golan...@googlegroups.com
If you're doing this a lot for single characters, you may want to make
a slice of runes, append to that, and convert the slice to a string at
the end. You're creating a new, full string every time you use string
+= x or string = string + x

Patrick Mylund Nielsen

unread,
May 11, 2012, 4:00:31 PM5/11/12
to perf...@gmail.com, Jan Mercl, golan...@googlegroups.com
Actually, you may want to do it anywhere you're doing excessive
concatenation, even when it's multiple characters -- you can use a
[]string, and run strings.Join at the end:
http://golang.org/pkg/strings/#Join. Join creates a slice of bytes of
the final size, writes all the strings from the []string to it, and
returns the byte slice cast to a string.

dlin

unread,
May 11, 2012, 10:49:03 PM5/11/12
to golan...@googlegroups.com
Here are my sample

func main() {
s := "abc"
c := byte('A')
s += string(c)
fmt.Println("Hello, playground",s ,c)

Nguyên Nguyễn Văn Cao

unread,
May 12, 2012, 9:52:13 PM5/12/12
to golan...@googlegroups.com
Good to see a Vietnamese here!
Hope you found your answer

Vào 23:47:32 UTC+7 Thứ sáu, ngày 11 tháng năm năm 2012, Thanh Hai Nguyen đã viết:

Brian Sturgill

unread,
May 17, 2014, 3:25:32 PM5/17/14
to golan...@googlegroups.com
I'm not sure your sample does what you want it to.... a byte is 256 bits, unicode runes can be larger than that.
s += string('A') will let larger unicode characters work as well.

On a related note, I was please to see that string([]rune) also works as you would hope it would.

Peter Nguyen

unread,
May 20, 2014, 2:23:34 AM5/20/14
to golan...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages