golang: Get last character of a string

A very quick one here. I needed to get the last character of a string in golang, but thinking like a PHP developer I was looking for an equivalent to substr($var, -1);.

As it turns out, you actually do it using slices

newVal := val[len(val)-1:]

This says “start at string length, minus 1 and give me everything to the end”

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Carl Menezes 2015-10-22

You can just use val[len(val)-1]

bmilesp 2018-10-03

@Carl Menezes that will return a byte value.

If you want a string returned OP’s original answer is best.

Leave a comment?

Leave a Reply