How to differentiate empty string and nothing in a map [duplicate] - go

This question already has answers here:
How to check if a map contains a key in Go?
(11 answers)
Closed 7 years ago.
The following code yields true. So I'm wondering for map[string]string in Golang, is there a way to differentiate empty string and nothing?
package main
import "fmt"
func main() {
m := make(map[string]string)
m["abc"] = ""
fmt.Println(m["a"] == m["abc"]) //true
}

If by "nothing" you mean that the element is not in the map you can use the ok idiom:
val, ok := myMap["value"] // ok is true if value was in the map
You can find more information in Effective Go.

Related

golang: passing pointer to struct to function doesn't update that struct's field in called function [duplicate]

This question already has answers here:
Change values while iterating
(4 answers)
Range references instead values
(8 answers)
increment a struct var in a range loop [duplicate]
(1 answer)
How to return changed values of slice from function? [duplicate]
(2 answers)
Why can't I change the values in a range of type structure?
(2 answers)
Closed 3 days ago.
I am new to Go. I've encountered an issue with Go pointers and don't have an explanation for the unexpected behavior.
I am using using Go 1.20 on RedHat.
Here is my test case:
package main
import (
"fmt"
)
type FileStruct struct {
readyToSend int
}
func sendFile(fileStr *FileStruct) {
fileStr.readyToSend = 2
}
func readFileFeeder(filesArr []FileStruct) {
filesArr[0].readyToSend = 1
for _, file := range filesArr {
fmt.Printf("TYPE=%T\n", &file)
sendFile(&file)
fmt.Printf("After range readyToSend=%v\n", filesArr[0].readyToSend)
}
fmt.Printf("TYPE=%T\n", &filesArr[0])
sendFile(&filesArr[0])
}
func main() {
var file1 *FileStruct = new(FileStruct)
filesArr := make([]FileStruct, 1)
filesArr[0] = *file1
fmt.Printf("Before readyToSend=%v\n", filesArr[0].readyToSend)
readFileFeeder(filesArr)
fmt.Printf("After readyToSend=%v\n", filesArr[0].readyToSend)
}
output:
==\> go run test.go
Before readyToSend=0
TYPE=\*main.FileStruct
After range readyToSend=1
TYPE=\*main.FileStruct
After readyToSend=2
How come when I call sendFile(&file) inside the for loop the value of fileStr.readyToSend doesn't get updated?
When I call sendFile(&filesArr[0]) right after the for loop the value gets updated as expected.
I would expect that fileStr.readyToSend would get updated to 2 in both cases.
How would you update this sample code to make this work?
Thanks

extract values from map interface [duplicate]

This question already has answers here:
How to convert interface{} to string?
(4 answers)
Closed 1 year ago.
below is my code
func main() {
var a interface{}
b := make(map[string]interface{})
b["mac_addr"] = "fa:16:3e:ba:95:bd"
b["type"] = "fixed"
b["addr"] = "1.1.1.1"
a = b
fmt.Println(a)
}
a gives me output
map[addr:1.1.1.1 mac_addr:fa:16:3e:ba:95:bd type:fixed]
issue is how do I access value of addr from a
use assert
val,ok:=a.(map[string]interface{})
if ok {
fmt.println(val["addr"])
}

Method prints correct data but returns unedited data in Go [duplicate]

This question already has answers here:
Struct field reverts [duplicate]
(1 answer)
How to set and get fields in struct's method
(3 answers)
Assign a new value to a struct field
(2 answers)
object variable is not getting updated in Golang [duplicate]
(1 answer)
Unable to set the property of a struct [duplicate]
(1 answer)
Closed 1 year ago.
This is my second day of learning Go and I'm trying to better understand structs and methods, so apologies in advance if this questions is a bit basic. Why does this program print the edited data inside the method, but by the time it gets back to main, what's printed is the original data passed to the struct?
package main
import ( "fmt" )
type Person struct{
firstName string
lastName string
}
func (p Person) updateName(newName string) string{
p.firstName = newName
fmt.Println(p.firstName, p.lastName) //prints "Jane Doe"
return newName + " " + p.lastName
}
func main() {
p := Person{"John", "Doe"}
p.updateName("Jane")
fmt.Println(p) //prints "{John Doe}"
}
Thanks in advance!

Golang r.URL.Query("x") does not return the full value with special characters [duplicate]

This question already has answers here:
Characters allowed in GET parameter
(7 answers)
Closed 9 months ago.
I was using r.URL.Query("model") to retrieve a url param. Lets say "https://example.com?model=345;1"
My expected behaviour is to retrieve: 345;1
But I only receive: 345
Is there a specific meaning behind it? and how i can force to get the full value. I am quite new go.
Code example
As LeGEC indicated the problem is due the fact that the semi-colon (;) is a character that has (or could have) special meaning in URLs.
You can use "%#v" in your Go Printf example to see how Go parsed the query string:
package main
import "fmt"
import "net/url"
import "log"
func main() {
u, err := url.Parse("https://example.com?model=345;1")
if err != nil {
log.Fatal(err)
}
q := u.Query()
fmt.Printf("%#v",q)
}
Gives
url.Values{"1":[]string{""}, "model":[]string{"345"}}
You could use u.RawQuery to get the entire string "model=345;1" and then parse it yourself. Not ideal, but perhaps a quick workaround.

How do I make a GO program wait until there is user input? [duplicate]

This question already has answers here:
How can I read from standard input in the console?
(12 answers)
Closed 7 years ago.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println("insert y value here: ")
input := bufio.NewScanner(os.Stdin)
fmt.Println(input.Text)
}
How do I make the program wait, until the user inputs data?
Scanner isn't really ideal for reading command line input (see the answer HectorJ referenced above), but if you want to make it work, it's a call to Scan() that you're missing (also note that Text() is a method call):
func main() {
fmt.Print("insert y value here: ")
input := bufio.NewScanner(os.Stdin)
input.Scan()
fmt.Println(input.Text())
}

Resources