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?
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.
Initializing Strings in GoLangexclamation := "!" fmt. Println(result) // prints "Hello, Dan!"
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.
A string in Go is a value. Thus, a string cannot be nil .
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With