Questions tagged [go]

Go is an open-source programming language, with a syntax loosely derived from C. It's statically typed, with limited dynamic typing capabilities; it also features automatic memory management, built-in concurrency primitives, variable-length arrays – called slices –, and a large standard library.

Filter by
Sorted by
Tagged with
1329 votes
11 answers

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?
grokus's user avatar
  • 18.1k
960 votes
19 answers

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 ...
Randy Sugianto 'Yuku''s user avatar
892 votes
12 answers

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?
aeter's user avatar
  • 12.1k
805 votes
9 answers

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 ...
Kevin Burke's user avatar
  • 61.5k
766 votes
9 answers

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?
tatsuhirosatou's user avatar
755 votes
10 answers

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 ...
hardPass's user avatar
  • 19.1k
755 votes
14 answers

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 ...
carbocation's user avatar
  • 8,830
750 votes
15 answers

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?
devyn's user avatar
  • 16.7k
700 votes
17 answers

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"`...
fnr's user avatar
  • 9,047
658 votes
14 answers

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?
Sridhar Ratnakumar's user avatar
589 votes
4 answers

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 ...
liamzebedee's user avatar
  • 14.1k
560 votes
15 answers

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 ...
Fabien's user avatar
  • 12.5k
559 votes
16 answers

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 ...
Rahul's user avatar
  • 11.1k
551 votes
8 answers

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 ...
Carnegie's user avatar
  • 5,645
548 votes
11 answers

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]...
Derrick Zhang's user avatar
541 votes
13 answers

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?
g06lin's user avatar
  • 5,735
539 votes
3 answers

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 *...
Marcus Vinícius Monteiro's user avatar
532 votes
10 answers

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?
sofire's user avatar
  • 5,437
528 votes
11 answers

When is 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 ...
Charlie Parker's user avatar
526 votes
5 answers

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} } ...
Zef Hemel's user avatar
  • 6,507
484 votes
9 answers

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 ...
Colonel Panic's user avatar
476 votes
11 answers

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?
Richard's user avatar
  • 10.2k
473 votes
19 answers

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?
Anish Shah's user avatar
  • 7,701
470 votes
8 answers

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?
Chris's user avatar
  • 8,268
469 votes
9 answers

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
user avatar
448 votes
25 answers

What should be the values of GOPATH and GOROOT?

I'm trying to install doozer like this: $ goinstall I get these errors. goinstall: os: go/build: package could not be found locally goinstall: fmt: go/build: package could not ...
jshen's user avatar
  • 11.5k
447 votes
19 answers

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?
vosmith's user avatar
  • 4,958
445 votes
6 answers

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 ...
Martin Redmond's user avatar
437 votes
5 answers

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?
Matt Joiner's user avatar
435 votes
13 answers

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....
wei2912's user avatar
  • 6,161
431 votes
12 answers

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 ...
A-letubby's user avatar
  • 8,474
413 votes
10 answers

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 := ...
Saswat Padhi's user avatar
  • 6,084
409 votes
16 answers

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
tomcam's user avatar
  • 4,685
409 votes
5 answers

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.
eouti's user avatar
  • 5,338
408 votes
9 answers

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 ...
Owen Allen's user avatar
  • 11.4k
398 votes
4 answers

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 ...
xpt's user avatar
  • 20.6k
392 votes
9 answers

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" "" "...
Ladislav Prskavec's user avatar
379 votes
12 answers

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#....
Dante's user avatar
  • 10.7k
361 votes
10 answers

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 ...
Seth Hoenig's user avatar
  • 7,047
359 votes
30 answers

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 and it fails with the following error: package cannot download, $GOPATH not set. For more details ...
David Saintloth's user avatar
349 votes
18 answers

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 . Where he ...
ekanna's user avatar
  • 5,472
340 votes
11 answers

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 ...
salezica's user avatar
  • 74.3k
339 votes
15 answers

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.
Brad Peabody's user avatar
  • 10.9k
333 votes
13 answers

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)?
theglauber's user avatar
  • 28.4k
325 votes
5 answers

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 ...
jonaz's user avatar
  • 3,784
324 votes
23 answers

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] ...
Anchal Sarraf's user avatar
322 votes
9 answers

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 ...
TomJ's user avatar
  • 5,389
320 votes
8 answers

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 ...
user avatar
320 votes
10 answers

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 ...
user avatar
310 votes
2 answers

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 ...
Simone Carletti's user avatar

2 3 4 5