73,771
questions
1393
votes
11
answers
1.5m
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?
993
votes
20
answers
733k
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 ...
928
votes
13
answers
522k
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?
831
votes
10
answers
658k
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
...
811
votes
10
answers
809k
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".
And in Java, I can do in this way:
String s = "ab" + "c" // s is "abc"
how can I concat two ...
800
votes
14
answers
635k
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 ...
790
votes
9
answers
635k
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?
787
votes
15
answers
561k
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?
735
votes
18
answers
783k
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"`...
697
votes
15
answers
523k
views
How to check if a file exists in Go?
Go's standard library does not have a function solely intended to check if a file exists or not (like Python's os.path.exists). What is the idiomatic way to do it?
607
votes
4
answers
181k
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 ...
593
votes
14
answers
511k
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
...
585
votes
16
answers
657k
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 ...
570
votes
8
answers
421k
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 ...
569
votes
13
answers
616k
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?
563
votes
3
answers
85k
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 *...
561
votes
10
answers
667k
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?
551
votes
11
answers
509k
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]...
548
votes
11
answers
256k
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 ...
541
votes
5
answers
160k
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}
}
...
503
votes
8
answers
203k
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?
502
votes
9
answers
343k
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 ...
501
votes
11
answers
577k
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?
500
votes
20
answers
448k
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?
497
votes
20
answers
755k
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?
489
votes
5
answers
695k
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?
486
votes
9
answers
471k
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
466
votes
12
answers
232k
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 ...
464
votes
25
answers
641k
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 ...
464
votes
13
answers
253k
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....
458
votes
6
answers
448k
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 ...
445
votes
8
answers
451k
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 ...
444
votes
17
answers
577k
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/...
438
votes
10
answers
508k
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 := ...
428
votes
6
answers
531k
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.
426
votes
4
answers
163k
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 ...
402
votes
9
answers
628k
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"
&...
393
votes
13
answers
478k
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#....
376
votes
11
answers
416k
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 ...
370
votes
28
answers
789k
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 ...
361
votes
4
answers
262k
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,...
360
votes
24
answers
711k
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]
...
360
votes
19
answers
352k
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 ...
359
votes
11
answers
205k
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 ...
356
votes
16
answers
356k
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.
346
votes
5
answers
389k
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 ...
338
votes
13
answers
250k
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)?
337
votes
8
answers
346k
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 ...
334
votes
11
answers
189k
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 ...
329
votes
9
answers
390k
views
Handling JSON Post Request in Go
So I have the following, which seems incredibly hacky, and I've been thinking to myself that Go has better designed libraries than this, but I can't find an example of Go handling a POST request of ...