74,477 questions
1436
votes
12
answers
1.6m
views
How to check if a map contains a key in Go?
I know I can iterate over a map m with
for k, v := range m { ... }
and look for a key, but is there a more efficient way of testing for a key's existence in a map?
1019
votes
20
answers
799k
views
How to efficiently concatenate strings in go
In Go, a string is a primitive type, which means it is read-only, and every manipulation of it will create a new string.
So if I want to concatenate strings many times without knowing the length of ...
958
votes
13
answers
577k
views
How do you write multiline strings in Go?
Does Go have anything similar to Python's multiline strings:
"""line 1
line 2
line 3"""
If not, what is the preferred way of writing strings spanning multiple lines?
858
votes
11
answers
713k
views
Concatenate two slices in Go
I'm trying to combine the slice [1, 2] and the slice [3, 4]. How can I do this in Go?
I tried:
append([]int{1,2}, []int{3,4})
but got:
cannot use []int literal (type []int) as type int in append
...
843
votes
11
answers
881k
views
How to convert an int value to string in Go?
i := 123
s := string(i)
s is 'E', but what I want is "123"
Please tell me how can I get "123".
824
votes
15
answers
700k
views
What is an idiomatic way of representing enums in Go?
I'm trying to represent a simplified chromosome, which consists of N bases, each of which can only be one of {A, C, T, G}.
I'd like to formalize the constraints with an enum, but I'm wondering what ...
815
votes
15
answers
606k
views
Optional Parameters in Go?
Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?
808
votes
9
answers
690k
views
Is there a foreach loop in Go?
Is there a foreach construct in the Go language?
Can I iterate over a slice or array using a for?
758
votes
19
answers
832k
views
How to print struct variables in console?
How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`...
725
votes
15
answers
569k
views
How to check if a file exists in Go?
Does the Go standard library have a function which checks if a file exists (like Python's os.path.exists).
Is there an idiomatic way to check file existence / non-existence?
619
votes
14
answers
573k
views
What is the idiomatic Go equivalent of C's ternary operator?
In C/C++ (and many languages of that family), a common idiom to declare and initialize a variable depending on a condition uses the ternary conditional operator :
int index = val > 0 ? val : -val
...
618
votes
4
answers
194k
views
What are the use(s) for struct tags in Go?
In the Go Language Specification, it mentions a brief overview of tags:
A field declaration may be followed by an optional string literal tag,
which becomes an attribute for all the fields in the ...
599
votes
16
answers
706k
views
How to find the type of an object in Go?
How do I find the type of an object in Go? In Python, I just use typeof to fetch the type of object. Similarly in Go, is there a way to implement the same ?
Here is the container from which I am ...
589
votes
13
answers
662k
views
Reading a file line by line in Go
I'm unable to find file.ReadLine function in Go.
How does one read a file line by line?
585
votes
8
answers
460k
views
Format a Go string without printing?
Is there a simple way to format a string in Go without printing the string?
I can do:
bar := "bar"
fmt.Printf("foo: %s", bar)
But I want the formatted string returned rather than printed so I can ...
583
votes
3
answers
93k
views
Function declaration syntax: things in parenthesis before function name
I'm sorry I couldn't be more specific in the question title, but I was reading some Go code and I encountered function declarations of this form:
func (h handler) ServeHTTP(w http.ResponseWriter, r *...
579
votes
10
answers
720k
views
How to assign string to bytes array
I want to assign string to bytes array:
var arr [20]byte
str := "abc"
for k, v := range []byte(str) {
arr[k] = byte(v)
}
Have another method?
568
votes
11
answers
275k
views
When does the init() function run?
I've tried to find a precise explanation of what the init() function does in Go. I read what Effective Go says but I was unsure if I understood fully what it said. The exact sentence I am unsure is ...
553
votes
11
answers
510k
views
How can I convert a zero-terminated byte array to string?
I need to read [100]byte to transfer a bunch of string data.
Because not all of the strings are precisely 100 characters long, the remaining part of the byte array is padded with 0s.
If I convert [100]...
549
votes
5
answers
169k
views
Pointers vs. values in parameters and return values
In Go there are various ways to return a struct value or slice thereof. For individual ones I've seen:
type MyStruct struct {
Val int
}
func myfunc() MyStruct {
return MyStruct{Val: 1}
}
...
534
votes
8
answers
229k
views
Difference between := and = operators in Go
What is the difference between the = and := operators, and what are the use cases for them? They both seem to be for an assignment?
533
votes
20
answers
846k
views
Contains method for a slice
Is there anything similar to a slice.contains(object) method in Go without having to do a search through each element in a slice?
527
votes
6
answers
812k
views
Convert string to integer type in Go?
I'm trying to convert a string returned from flag.Arg(n) to an int. What is the idiomatic way to do this in Go?
516
votes
9
answers
363k
views
How to multiply duration by integer?
To test concurrent goroutines, I added a line to a function to make it take a random time to return (up to one second)
time.Sleep(rand.Int31n(1000) * time.Millisecond)
However when I compiled, I got ...
513
votes
21
answers
483k
views
How to generate a random string of a fixed length in Go?
I want a random string of characters only (uppercase or lowercase), no numbers, in Go. What is the fastest and simplest way to do this?
510
votes
11
answers
614k
views
What is the best way to test for an empty string in Go?
Which method is best (most idomatic) for testing non-empty strings (in Go)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
Or something else?
499
votes
9
answers
501k
views
Does Go have "if x in" construct similar to Python? [duplicate]
How can I check if x is in an array without iterating over the entire array, using Go? Does the language have a construct for this?
Like in Python:
if "x" in array:
# do something
487
votes
14
answers
255k
views
How to avoid annoying error "declared and not used"
I'm learning Go but I feel it is a bit annoying that when compiling, I should not leave any variable or package unused.
This is really quite slowing me down. For example, I just wanted to declare a ...
479
votes
25
answers
685k
views
What should be the values of GOPATH and GOROOT?
I'm trying to install doozer like this:
$ goinstall github.com/ha/doozer
I get these errors.
goinstall: os: go/build: package could not be found locally
goinstall: fmt: go/build: package could not ...
472
votes
13
answers
280k
views
Checking the equality of two slices
How can I check if two slices are equal, given that the operators == and != are not an option?
package main
import "fmt"
func main() {
s1 := []int{1, 2}
s2 := []int{1, 2}
fmt....
471
votes
18
answers
650k
views
go get results in 'terminal prompts disabled' error for GitHub private repo
I created the private repo examplesite/myprivaterepo using the GitHub UI from my browser.
Then I went to my go directory (on the desktop) and cloned it:
$ cd $GOPATH
$ go get github.com/examplesite/...
467
votes
6
answers
474k
views
Iterating over all the keys of a map
Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:
m := map[string]string{ "key1":"val1", "key2":"val2" };
How do ...
466
votes
8
answers
520k
views
Removing packages installed with go get
I ran go get package to download a package before learning that I needed to set my GOPATH otherwise that package sullies my root Go install (I would much prefer to keep my Go install clean and ...
453
votes
10
answers
563k
views
Getting a slice of keys from a map
Is there any simpler/nicer way of getting a slice of keys from a map in Go?
Currently I am iterating over the map and copying the keys to a slice:
i := 0
keys := make([]int, len(mymap))
for k := ...
445
votes
6
answers
569k
views
Correct way to initialize empty slice
To declare an empty slice, with a non-fixed size,
is it better to do:
mySlice1 := make([]int, 0)
or:
mySlice2 := []int{}
Just wondering which one is the correct way.
435
votes
4
answers
178k
views
X does not implement Y (... method has a pointer receiver)
There are already several Q&As on this "X does not implement Y (... method has a pointer receiver)" thing, but to me, they seems to be talking about different things, and not applying to my ...
408
votes
9
answers
652k
views
How do I send a JSON string in a POST request in Go
I tried working with Apiary and made a universal template to send JSON to mock server and have this code:
package main
import (
"encoding/json"
"fmt"
&...
406
votes
13
answers
510k
views
How can I read from standard input in the console?
I would like to read standard input from the command line, but my attempts have ended with the program exiting before I'm prompted for input. I'm looking for the equivalent of Console.ReadLine() in C#....
405
votes
4
answers
310k
views
Golang why don't we have a set datastructure [closed]
I'm trying to solve a Go language exercise which requires me to have a set. I can create a set type but why doesn't the language come with one?
Go, having come from Google, where Guava also originated,...
391
votes
11
answers
463k
views
How to read/write from/to a file using Go
I've been trying to learn Go on my own, but I've been stumped on trying read from and write to ordinary files.
I can get as far as inFile, _ := os.Open(INFILE, 0, 0), but actually getting the content ...
380
votes
24
answers
792k
views
How to delete an element from a Slice in Golang
fmt.Println("Enter position to delete::")
fmt.Scanln(&pos)
new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
if i != pos {
new_arr[i] = arr[k]
...
375
votes
19
answers
385k
views
How to get the directory of the currently running file?
In nodejs I use __dirname . What is the equivalent of this in Golang?
I have googled and found out this article http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ . Where he ...
375
votes
28
answers
830k
views
How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?
I am trying to do a go get:
go get github.com/go-sql-driver/mysql
and it fails with the following error:
package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details ...
371
votes
11
answers
226k
views
Why would I make() or new()?
The introduction documents dedicate many paragraphs to explaining the difference between new() and make(), but in practice, you can create objects within local scope and return them.
Why would you ...
370
votes
16
answers
388k
views
How can I pretty-print JSON using Go?
Does anyone know of a simple way to pretty-print JSON output in Go?
I'd like to pretty-print the result of json.Marshal, as well as formatting an existing string of JSON so it's easier to read.
365
votes
5
answers
434k
views
Delete key in map
I have a map:
var sessions = map[string] chan int{}
How do I delete sessions[key]? I tried:
sessions[key] = nil,false;
That didn't work.
Update (November 2011):
The special syntax for deleting map ...
349
votes
11
answers
212k
views
What is a rune?
What is a rune in Go?
I've been googling but Golang only says in one line: rune is an alias for int32.
But how come integers are used all around like swapping cases?
The following is a function ...
345
votes
9
answers
375k
views
How to run test cases in a specified file?
My package test cases are scattered across multiple files, if I run go test <package_name> it runs all test cases in the package.
It is unnecessary to run all of them though. Is there a way to ...
341
votes
13
answers
260k
views
How to handle configuration in Go [closed]
What is the preferred way to handle configuration parameters for a Go program (the kind of stuff one might use properties files or ini files for, in other contexts)?
339
votes
2
answers
141k
views
Decoding JSON using json.Unmarshal vs json.NewDecoder.Decode
I'm developing an API client where I need to encode a JSON payload on request and decode a JSON body from the response.
I've read the source code from several libraries and from what I have seen, I ...