It usually will be something like this
func main() {
my_map := myFunc()
fmt.Println(my_map)
}
func myFunc() map[string]interface{} {
// .... create a map....
return map
}
when I run patterns like this, I almost always get a segfault when I try and print out my_map
.
This also happens if I return a []byte
type.
Now here's the thing: I think understand why returning a []byte
that was created inside myFunc()
would result in a segfault when printing it in main: The slice is referencing an array that was created inside myFunc
, so as soon as myFunc
returns, that array is deleted by garbage collection, and hence the segfault.
I'm going to assume something similar is happening with the map.
In C++, it would simply create a copy of the map, and return that --> no problem. Same if i returned an array.
Why, in go, can't I simply return a created map, and what would be the best way to return a map (created inside a function) without resulting in a segfault as soon as that function returns to main?
func twitterRequest(query string, token string) map[string]interface{} {
req, err := http.NewRequest("GET", query, nil)
if err != nil {
log.Fatal(err.Error())
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
client := &http.Client{}
resp, err2 := client.Do(req)
if err2 != nil {
log.Fatal(err.Error())
}
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
var jsonResp interface{} // turns into map[string]interface{}
err = json.Unmarshal(respBody, &jsonResp)
if err != nil {
log.Fatal("wrong")
}
return jsonResp.(map[string]interface{})
}
func searchTweets(queries string, token string) {
builder := strings.Builder{}
builder.WriteString(tweetSearchUrl)
builder.WriteString("q=")
builder.WriteString(queries)
queryUrl := url.QueryEscape(builder.String())
map1 := twitterRequest(queryUrl, token)
fmt.Println(map1) // SEG FAULT HERE
}