Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my GoLang program which invokes a REST API, i need to collect the responses from different REST API's which return slices of pointers of the same struct.
I am attempting to concatenate the slices of pointers using append and i am getting error similar to what is shown below.
I think append does not support such an operation , is there any alternative to this ?
cannot use response (type []*string) as type *string in append
A go playground link for the problem ,i am trying to demonstrate is given here.
https://play.golang.org/p/lnzSd2kbht0
package main
import (
"fmt"
)
func main() {
var fruits []*string
response := GetStrings("Apple")
fruits = append(fruits, response...)
response = GetStrings("Banana")
fruits = append(fruits, response...)
response = GetStrings("Orange")
fruits = append(fruits, response...)
if fruits == nil || len(fruits) == 0 {
fmt.Printf("Nil Slice")
} else {
fmt.Printf("Non nil")
fmt.Printf("%v", fruits)
}
}
func GetStrings(input string) []*string {
var myslice []*string
myslice = append(myslice, &input)
return myslice
}
I cannot change the REST API or the function signature to return the slice of structs itself.
To append all elements of a slice to another slice, use:
resultSlice=append(slice1, slice2...)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am unable to parse json that has string keys and array as value ending up with json: Unmarshal(non-pointer map[string]interface {}) error.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var s map[string]interface{}
err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), s)
if err != nil {
panic(err)
}
fmt.Println("Nice parse!")
}
https://go.dev/play/p/AXlF8I-f9-p
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. Add &s as a parameter
err := json.Unmarshal([]byte("{\"a\":[1,2,3]}"), &s)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to write a program using Go which perform tuple or variable unpacking as below in python
url = ('https://www.amazon.com/War-Art-Through-Creative-Battles' '/dp/1936891026/?keywords=war+of+art')
domain , *rest , isbn = url.split("/")[2:-1]
So I have written code as below using Go
package main
import (
"fmt"
"strings"
)
func main() {
var a string
a = ("https://www.amazon.com/War-Art-Through-Creative-Battles" +
"/dp/1936891026/?keywords=war+of+art") // dont use ' quotes
fmt.Println(a)
split_a := strings.Split(a, "/")
fmt.Println(split_a)
var rest []string
var domain string
var isbn string
domain, rest, isbn = split_a[2:-1]
}
and getting cannot assign 1 values to 3 variables compiler WrongAssignCount.
I understand the error as it reflects what I am trying to achieve, I am trying to find out the methods to achieve this and finally thought of checking with others. Any suggestions much appreciated.
Thank you.
This is just string manipulation, so no one right answer. Since your source is a
URL, I would say net/url is a good starting point:
package main
import (
"net/url"
"path"
)
func main() {
p, e := url.Parse(
"https://www.amazon.com/" +
"War-Art-Through-Creative-Battles/dp/1936891026/?keywords=war+of+art",
)
if e != nil {
panic(e)
}
rest, isbn := path.Split(path.Clean(p.Path))
println(
p.Host == "www.amazon.com",
rest == "/War-Art-Through-Creative-Battles/dp/",
isbn == "1936891026",
)
}
https://golang.org/pkg/net/url
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Is it possible to have multiple receivers on a single function? In other words, a single function can belong to two or more structs?
Say I have
type Struct1 struct {
foo.Client
}
func CreateClient() struct1 {
return struct1{
ClientID: cId,
// ...
}
}
func (s *Struct1) MyFunc( // ... ) {}
But I also want to be able to associate MyFunc with another struct (different package):
type Struct2 struct {
lgr log.logger
}
func NewStruct2 (l *log.logger) (*Struct2, err) {
return &Struct2{mylog: *l}, nil
}
So what I want to actually have is:
func (s1 *Struct1, s2 *Struct2) MyFunc( // ... ) {}
"Is it possible to have multiple receivers on a single function?" -- It is not possible.
https://golang.org/ref/spec#Method_declarations
The receiver is specified via an extra parameter section preceding the
method name. That parameter section must declare a single non-variadic
parameter, the receiver.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a map string that looks like this
map[first:[hello] second:[world]]
The problem is that when I iterate over it and return the values they return [hello] [world] and I want them to just return hello world
// currentMap is of type map[interface{}]interface{} originally
newStringMap := make(map[string]interface{})
for k, v := range currentMap {
newStringMap[k.(string)] = v
}
return newStringMap
How can this be done?
From the below information provided by you:
when I iterate over it and return the values they return [hello] [world]
It seems that your currentMap actually stores string slices []string as values, behind the interface{} type. Assuming that above line means that you see this when printing the map using fmt.Println(), or similar functions.
map[first:[hello] second:[world]]
Here's a possible reproduction & solution of your problem::
package main
import (
"fmt"
)
func main() {
currentMap := make(map[interface{}]interface{})
currentMap["first"] = []string{"hello"}
currentMap["second"] = []string{"world"}
newStringMap := make(map[string]interface{})
fmt.Println("Problem:")
fmt.Printf("%v\n", currentMap)
fmt.Println("\nSolution:")
for k, v := range currentMap {
lst, ok := v.([]string)
//fmt.Println(lst, ok)
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}
}
fmt.Printf("%v\n", newStringMap)
}
Which outputs to:
Problem:
map[first:[hello] second:[world]]
Solution:
map[first:hello second:world]
Try it here
https://play.golang.org/p/5XAA3m6MDX_b
It's not necessary that the content stored in currentMap is always of similar type. (if it is, then why would interface{} ever be used). Which means, don't forget your error-checking. I have tried to cover the same. You may need to add some more, based on the possible actual types in the map, similar to this section:
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to unmarshal json data. The slice inside is deliberately without quotes, because this is what I am getting from https (added manually \ before ")
data:="{\"queryEndTime\" : \"2017-11-15T14:39:00Z\", \"message\" : [{\"spamScore\":67,\"phishScore\":0}]}"
into Message struct:
type Message struct {
QueryEndTime string `json:"queryEndTime"`
Message []string `json:"message"`
}
but I am getting correct QueryEndTime and empty Message. I tried to change Message type but it always stays empty
var message Message
json.Unmarshal([]byte(data), &message)
fmt.Printf("QueryEndTime: %s\nMessage: %s\n", message.QueryEndTime, message.Message)
QueryEndTime: 2017-11-15T14:39:00Z
Message: []
See it in go playground https://play.golang.org/p/on0_cSKb0c.
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
QueryEndTime string `json:"queryEndTime"`
// you need to use a struct can use anon struct
Message []struct {
SpamScore int `json:"spamScore"`
PhishScore int `json:"phishScore"`
} `json:"message"`
}
func main() {
var message Message
// You can use backticks to for your example JSON, so that you don't have to escape anything.
data := `{
"queryEndTime" : "2017-11-15T14:39:00Z",
"message" : [
{"spamScore":67, "phishScore":0}
]
}`
// please check for errors
err := json.Unmarshal([]byte(data), &message)
if err != nil {
fmt.Println(err)
}
// +v prints structs very nicely
fmt.Printf("%+v\n", message)
}
https://play.golang.org/p/Mu3WZCej3L
Have fun!