Ron
(ron)
1
I need help understanding how to get the following code to work:
package main
import "fmt"
type compensation struct {
salary int
insurance bool
stocksOptions bool
}
type employee struct {
name string
id int
totalComp *compensation
}
func main() {
newEmployee := employee{
name: "gary",
id: 1,
totalComp: &compensation{
salary: 100,
insurance: true,
stocksOptions: true,
},
}
var anotherNewEmployee = new(employee)
anotherNewEmployee.id = 2
anotherNewEmployee.name = "rich"
anotherNewEmployee.totalComp.insurance = false
fmt.Println(anotherNewEmployee)
anotherNewEmployee.totalComp.insurance = true
fmt.Println(anotherNewEmployee.totalComp.insurance)
fmt.Println(newEmployee.totalComp.salary)
newEmployee.totalComp.salary = 4
fmt.Println(newEmployee.totalComp.salary)
}
I get an error when I try to set anotherNewEmployee.totalComp.insurance = false
, I’m not sure I understand how to give this a value.
NobbZ
(Norbert Melzer)
2
You haven’t created a compensation
before trying to modify it. So you basically try to do ((*compensation)nil).insurance = false
.
petrus
(petrus)
3
anotherNewEmployee.totalComp
is nil
, so add anotherNewEmployee.totalComp = new(compensation)
.
package main
import "fmt"
type compensation struct {
salary int
insurance bool
stocksOptions bool
}
type employee struct {
name string
id int
totalComp *compensation
}
func main() {
newEmployee := employee{
name: "gary",
id: 1,
totalComp: &compensation{
salary: 100,
insurance: true,
stocksOptions: true,
},
}
var anotherNewEmployee = new(employee)
anotherNewEmployee.id = 2
anotherNewEmployee.name = "rich"
anotherNewEmployee.totalComp = new(compensation)
anotherNewEmployee.totalComp.insurance = false
fmt.Println(anotherNewEmployee)
anotherNewEmployee.totalComp.insurance = true
fmt.Println(anotherNewEmployee.totalComp.insurance)
fmt.Println(newEmployee.totalComp.salary)
newEmployee.totalComp.salary = 4
fmt.Println(newEmployee.totalComp.salary)
}
https://play.golang.org/p/poxtodoeUeB
&{rich 2 0xc00002c040}
true
100
4
petrus
(petrus)
4
syntax error: unexpected nil, expecting )
NobbZ
(Norbert Melzer)
5
That was some pseudo code that should tell about the issue.
Ron
(ron)
6
Perfect, thank you for explaining that!
system
(system)
Closed
7
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.