golang: Get last character of a string

This article was published 5 years ago. Due to the rapidly evolving world of technology, some concepts may no longer be applicable.

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”

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?