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 2 years ago.
Improve this question
I don't understand why this doesn't work for this type of structure.
package main
import (
"fmt"
)
var myStruct struct {
number float64
word string
toggle bool
}
myStruct.number = 3.14
myStruct.word = "pie"
myStruct.toggle = true
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
If I try to change myStruct.number outside main, I get a compilation error syntax error: non-declaration statement outside function body, but it works fine inside the function. With variables or other types of data structures, it works fine to change values outside main scope, but not with struct.
The program is an example from Head first Go, and even if I searched at least three more books and google for more information, I haven't found something similar that would be better explained.
https://play.golang.org/p/brocZzWuRae
package main
import (
"fmt"
)
var myStruct = struct {
number float64
word string
toggle bool
}{
number: 3.14,
word: "pie",
toggle: true,
}
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
https://go.dev/play/p/L2IJp-ehA2S
The following program provides me the required output (ccc09e). But this is correct approach or this can be improved.
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string
}
func main() {
empJson := `[{"name":"ccc09e"}]`
var emp []People
json.Unmarshal([]byte(empJson), &emp)
s := fmt.Sprintf("%v", emp[0])
s = s[1 : len(s)-1]
fmt.Println(s)
}
I got the required output https://go.dev/play/p/L2IJp-ehA2S and I need improvement to the program.
Looks like you want the Name of the First element of People array in s
No need to do string manipulations. Just access it directly
package main
import (
"encoding/json"
"fmt"
)
type People struct {
Name string
}
func main() {
empJson := `[{"name":"ccc09e"}]`
var emp []People
json.Unmarshal([]byte(empJson), &emp)
s := emp[0].Name
fmt.Println(s)
}
https://go.dev/play/p/O2hiGuSyM53
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 2 years ago.
Improve this question
I'm stuck on decoding a JSON in swift.
I've got the following code in a playground with a JSON that has 10 fields. When i try to decode the data I get the following Error
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
But this error does not seem to happen if I take out e.g. "ninth" and "tenth" or 2 of any of the other fields so only 8 fields remain in the struct.
Is there a limitation of only be able to have 8 fields decoded? Am I missing something?
is there anything i can do to overcome this issue?
My code snippet:
let decoder = JSONDecoder()
struct Positions: Codable {
let first : String
let second: String
let third: String
let forth: String
let fith: String
let sixth: String
let seventh: String
let eigth: String
let nineth: String
let tenth: String
}
var positions = """
{
"first" : "first",
"second": "second",
"third": "third",
"forth": "forth",
"fith": "fith",
"sixth": "sixth",
"seventh": "seventh",
"eigth": "eigth",
"nineth": "nineth",
"tenth": "tenth"
}
""".data(using: .utf8)
let result = try decoder.decode(Positions.self, from: positions!)
print("tr \(result)")
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm a bit new to golang coming from a nodejs background. I'm a bit confused as to why certain functions have a function signature in the following format
function readContents(var1 type, var2 *type)
If we consider the above function, readContents, reads contents into a pointer of var2. Is this a standard practice in the go language where you pass parameters in and expect them to have return values. A practical example is here https://github.com/vmihailenco/msgpack. If you look at the quickstart it has the following code
err = msgpack.Unmarshal(b, &item)
I would normally expect it to return the value rather than modify the incoming value in &item.
Return values are generally preferred.
The caller must specify the type of the target value to msgpack.Unmarshal. The Unmarshal function can be restructured to use a return value like this:
func Unmarshal(p []data, exampleValueOfType interface{}) (interface{}, error)
The calling code will look something like this:
v, err := msgpack.Unmarshal(b, (*X)(nil))
if err != nil {
// handle error
}
x := v.(*X)
It's simpler for the caller to pass to pass a target value. This avoids the type assertion and mentioning the type twice in the code:
var x X
if err := msgpack.Unmarshal(b, &x) {
// handle error
}
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 4 years ago.
Improve this question
How to bind json stringify data in golang custom struct type?
js ajax
$.ajax({
type: "POST"
, url : url
, data : JSON.stringify('{"nowBlockPositionX":3,"nowBlockPositionY":0,"nowBlock":{"O":0}}')
})
go custom struct
type demo struct {
nowBlockPositionX int `form:"nowBlockPositionX" json:"nowBlockPositionX"`
NowBlockPositionY int `form:"nowBlockPositionY" json:"nowBlockPositionY"`
NowBlock map[string]int `form:"nowBlock" json:"nowBlock" query:"nowBlock"`
}
don't binding this
demo := new(demo)
if err := c.Bind(demo); err != nil {
c.Logger().Error(err)
}
First, fix the demo struct. The field in the struct need to be exported. Just change the first character of each field to be in uppercase.
Then remove the form: and query: tags. You only need the json: tag.
type demo struct {
NowBlockPositionX int `json:"NowBlockPositionX"`
NowBlockPositionY int `json:"NowBlockPositionY"`
NowBlock map[string]int `json:"NowBlock"`
}
There are also few problems appear on your javascript code, on the $.ajax statement.
Do this two things:
Set the content type header to application/json.
Remove the JSON.stringify() since your data already in string.
Working code:
$.ajax({
url : url,
type: "POST",
dataType: "json",
contentType: "application/json",
data: '{"nowBlockPositionX":3,"nowBlockPositionY":0,"nowBlock":{"O":0}}'
})
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 5 years ago.
Improve this question
I have a very simple http resonse in my server where i json encode a struct. But its sending a blank of just {}
I don't know if i am doing it wrong but i get no errors. This is my json encode:
// Set uuid as string to user struct
user := User{uuid: uuid.String()}
fmt.Println(user) // check it has the uuid
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusCreated)
json.NewEncoder(responseWriter).Encode(user)
On the recieving end the data has:
Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}
Why does it not give me the uuid data? Am i doing something wrong with my encoding?
Export the field name by making the first character of the identifier's name a Unicode upper case letter (Unicode class "Lu").
Try this:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type User struct {
Uuid string
}
func handler(responseWriter http.ResponseWriter, r *http.Request) {
user := User{Uuid: "id1234657..."} // Set uuid as string to user struct
fmt.Println(user) // check it has the uuid
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusCreated)
json.NewEncoder(responseWriter).Encode(user)
}
func main() {
http.HandleFunc("/", handler) // set router
err := http.ListenAndServe(":9090", nil) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
output(http://localhost:9090/):
{"Uuid":"id1234657..."}