This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 6 years ago.
I am trying to cast a value to a struct which has a type of time.Time.
The value is:
t := time.Now()
format := "2006-01-02 15:04:05"
Then I am trying to put this into the struct:
response.SetAppData[0].LiveDate = time.Parse(format, t.String())
However I get the error of:
controllers/apps.go:1085: multiple-value time.Parse() in single-value context
I am not sure what I am doing wrong.
Thanks
It means that time.Parse returns two results time.Time and error values. You are assigning only to one variable.
You should do that:
response.SetAppData[0].LiveDate, err = time.Parse(format, t.String())
if err != nil {
// error handling here
}
Related
This question already has answers here:
Why can't I append to a slice that's the property of a struct in golang?
(1 answer)
Golang Operator Overloading
(1 answer)
How to modify the value of a simple type through pointer receiver method in Go?
(2 answers)
Struct is empty after Json unmarshal when accessed by another package
(1 answer)
Remove an element of a slice in a struct [duplicate]
(1 answer)
Closed 2 years ago.
I'm sure there's a good explanation for this, but I've not been able to find it. Can anyone help me understand what is happening the following code example?
package main
import (
"fmt"
)
type work struct {
data map[string]string
}
func (w work) doSome() {
w.data = make(map[string]string)
w.data["k1"] = "v1"
}
func main() {
work := work{}
work.doSome()
if work.data == nil {
fmt.Println("data is nil")
} else {
fmt.Println("data is", work.data)
}
}
This prints out data is nil, which is not what I expected. If I rework this to be a pointer type (i.e. *work) for doSome method , it initializes the struct's variable. I'd like to understand why these are different. I assume it's something to do with map being a pointer, of sorts, but haven't been able to find a good reference to explain this.
Playground link - https://play.golang.org/p/lTN11TRkRNj
With a value receiver (func (w work) doSome()) the function gets a copy of the work struct. When it sets w.data, it is set for that copy, not for the instance of work declared in main.
Maps are essentially reference types, so if you initialized the map in main, this would've worked:
func (w work) doSome() {
w.data["k1"] = "v1"
}
func main() {
work := work{data:map[string]string{}}
work.doSome()
}
Or, you should use a pointer receiver, so the work declared in main is sent to doSome as a pointer:
func (w *work) doSome() {
w.data = make(map[string]string)
w.data["k1"] = "v1"
}
func main() {
work := work{}
work.doSome()
}
This question already has an answer here:
How to print the address of struct variable in go
(1 answer)
Closed 3 years ago.
I have struct type and referring address of the variable, but it does not reflect latest value of the variable in the defer function.
type XY struct {
S string
}
func CloseP(x *XY) {
if x != nil {
fmt.Println("Pointer-Closing", x.S)
}
}
func main() {
xp2 := &XY{"Pointer-X2 First"}
fmt.Println(xp2)
defer CloseP( xp2 )
xp2 = &XY{"Pointer-X2 Second"}
fmt.Println(xp2)
}
Output
&{Pointer-X2 First}
&{Pointer-X2 Second}
Pointer-Closing Pointer-X2 First
Expected Output
0xc000086018
0xc000086018
Pointer-Closing Pointer-X2 Second
My questions are:
Why is it display with '&' in the actual output, where it suppose to print address of the variable.
Why defer function is not reflecting latest value of the 'xp2' variable ?
So for the point 2- I have implemented below function. Can someone tell me is this best way to resolve this problem.
func main() {
xp2 := XY{"Pointer-X2 First"}
defer CloseP( &xp2 )
xp2 = XY{"Pointer-X2 Second"}
}
Output is
Pointer-Closing Pointer-X2 Second
Why is it display with '&' in the actual output, where it suppose to print address of the variable
Take a look at the format options here:
https://golang.org/pkg/fmt/
Println is using the default %v, if you want to print the value of the pointer, you can use the %p format, like so:
fmt.Printf("Pointer-Closing %p\n", xp2)
Why defer function is not reflecting latest value of the 'xp2' variable ?
Take a look here:
https://blog.golang.org/defer-panic-and-recover
A deferred function's arguments are evaluated when the defer statement is evaluated.
So at the time the defer is evaluated there, the pointer is referencing the first object, so that output is as expected.
This question already has answers here:
Explain Type Assertions in Go
(3 answers)
Accessing Nested Map of Type map[string]interface{} in Golang
(2 answers)
Typed, nested map of map[string]interface{} returns "type interface {} does not support indexing"
(1 answer)
get value form nested map type map[string]interface{}
(2 answers)
how to access nested Json key values in Golang
(3 answers)
Closed 4 years ago.
I have something like this:
x1 := someFunctionWithAnInterfaceReturnValue()
and the underlying type is something like this:
x2 := map[string] string{"hello": "world"}
How would I access value in x1?
Essentially I want the equivalent of this for x1:
var value string = x2["hello"]
Use a type assertion:
x1 := someFunctionWithAnInterfaceReturnValue()
x2, ok := x1.(map[string]string)
if !ok {
// handle unexpected type
}
var value string = x2["hello"]
This question already has answers here:
Using Pointers in a for loop
(2 answers)
How to understand this behavior of goroutine?
(2 answers)
Golang Reusing Memory Address Copying from slice?
(2 answers)
Register multiple routes using range for loop slices/map
(1 answer)
Convert slice of string to slice of pointer to string
(2 answers)
Closed 9 months ago.
I am using a for range loop in Go to iterate through a slice of structs.
In each loop, I a pointer to the current item to a variable.
I am confused why the pointer changes value in the next loop.
For example this code:
package main
import "fmt"
type t struct {
val int
}
func main() {
l := []t{{1}, {2}}
var p *t
for _, i := range l {
fmt.Println("begin", p)
p = &i
fmt.Println("end", p)
}
}
I would expect to produce:
begin <nil>
end &{1}
begin &{1}
end &{2}
But actually does:
begin <nil>
end &{1}
begin &{2}
end &{2}
For reference, in my actual code, I am checking for a condition during the loop, and returning the current item and previous one. So I am trying to save a pointer to it, so that in the next iteration it will have access to the previous as well.
The problem is that you're taking the address of the loop/range variable and not the address of the item in slice. However, you're just making a lot of unnecessary work for yourself. For one, why don't you use the i, v := range or better yet i, _ := and then you can do i-1 to get the previous item? Secondly, even if you want it saved in a pointer, still use this syntax and then assign p = &l[i] so you have the address of the item in the slice rather than the address of the loop/range variable.
People are way too eager to use for/each style constructs when it's obviously better to work with the index... If you want index-1 on every iteration, using the index should be your go to way of doing that.
Building off Tim's comment, it seems like you can copy the value on each loop, instead of the pointer, and dereference it after.
package main
import "fmt"
type t struct {
val int
}
func main() {
l := []t{{1}, {2}}
var p t
var i t
for _, i = range l {
fmt.Println("begin", &p)
p = i
fmt.Println("end", &p)
}
}
Another option is to get the pointer to the current item by using the index:
package main
import "fmt"
type t struct {
val int
}
func main() {
l := []t{{1}, {2}}
var p *t
for index, _ := range l {
fmt.Println("begin", p)
p = &l[index]
fmt.Println("end", p)
}
}
This question already has answers here:
escape dictionary key double quotes when doing println dictionary item in Swift
(5 answers)
Closed 8 years ago.
For some reason, I just can't make this expression work:
let expandedBio: Dictionary<String,AnyObject> = ["name":"Saurabh", "profession":"developer", "language":"java", "employed": true]
if let employed : AnyObject = expandedBio["employed"] {
println("\(expandedBio[\"name\"]) is not available")
}
How do I output the println statement? I get the error
Unexpected "" character error in string interpolation
How do I do this right?
In current version of Swift you have to put value in its own constant/variable first, then use that.
if let employed : AnyObject = expandedBio["employed"] {
let t = expandedBio["name"]
println("\(t) is not available")
}