Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to initialise an empty string in Go

Tags:

go

In Go you can initialise an empty string (in a function) in the following ways:

var a string
var b = ""
c := ""

As far as I know, each statement is semantically identical. Is one of them more idiomatic than the others?

like image 681
jamesroutley Avatar asked Jan 17 '17 16:01

jamesroutley


People also ask

What is the best way to test for an empty string in go?

In this shot, we will learn to check if a string is empty or not. In Golang, we can do this by: Comparing it with an empty string. Evaluating the length of the string; if it's zero, then the string is empty, and vice versa.

How do you initialize a string in go?

Initializing Strings in GoLangexclamation := "!" fmt. Println(result) // prints "Hello, Dan!"

How do you assign an empty string?

As others mentioned the former can be achieved via std::string::empty() , the latter can be achieved with boost::optional<std::string> , e.g.: Save this answer. Show activity on this post. The default constructor initializes the string to the empty string.

Can a string be nil in GoLang?

A string in Go is a value. Thus, a string cannot be nil .


2 Answers

You should choose whichever makes the code clearer. If the zero value will actually be used (e.g. when you start with an empty string and concatenate others to it), it's probably clearest to use the := form. If you are just declaring the variable, and will be assigning it a different value later, use var.

like image 102
andybalholm Avatar answered Oct 07 '22 23:10

andybalholm


var a string

It's not immediately visible that it's the empty string for someone not really fluent in go. Some might expect it's some null/nil value.

var b = ""

Would be the most explicit, means everyone sees that it's a variable containing the empty string.

b := ""

The := assigment is so common in go that it would be the most readable in my opinion. Unless it's outside of a function body of course.

like image 28
Christian Avatar answered Oct 08 '22 01:10

Christian