How to resolve error Cannot use 'struct{ width, height float64 }{2.0, 3.0}' (type struct {...}) as the type struct {...}

309 views
Skip to first unread message

Richard Whatever

unread,
Aug 30, 2022, 10:48:21 AM8/30/22
to golang-nuts

I'm developing a mvc Golang server.

The model file is as follows:

type Object struct { ... TargetSize struct{ width, height float64 } `json:"targetSize"` ... }

The controller file is as follows:

func (c *GetObject) Get() []models.Object { return []models.Object{ {... struct{ width, height float64 }{2.0, 3.0}, ... },

I keep on getting the error of "Cannot use 'struct{ width, height float64 }{2.0, 3.0}' (type struct {...}) as the type struct {...}" and I don't know how to resolve this.



Dan Kortschak

unread,
Aug 30, 2022, 6:07:20 PM8/30/22
to golan...@googlegroups.com
You'll benefit from defining the type struct{ width, height float64 }
if you need to use it elsewhere. Also, for JSON de/serialisation, the
fields will need to be exported. This will also fix you compile.

Harris, Andrew

unread,
Aug 30, 2022, 6:07:52 PM8/30/22
to Richard Whatever, golang-nuts
I believe anonymous definitions of structs here is the cause. While equivalent, each anonymous definition is a distinct type.

From: golan...@googlegroups.com <golan...@googlegroups.com> on behalf of Richard Whatever <c.richa...@gmail.com>
Sent: Tuesday, August 30, 2022 7:46:47 AM
To: golang-nuts <golan...@googlegroups.com>
Subject: [go-nuts] How to resolve error Cannot use 'struct{ width, height float64 }{2.0, 3.0}' (type struct {...}) as the type struct {...}
 
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a6b7d86c-8ed6-4be1-a265-3761f3b8be67n%40googlegroups.com.

Richard Whatever

unread,
Aug 30, 2022, 9:49:51 PM8/30/22
to Harris, Andrew, golang-nuts
Thanks for the assistance. Issue resolved by naming "width" and "height" with the capital starting letter, "Width" and "Height". Looks like I'm still not familiar with the Go export syntax yet. 

Harris, Andrew <harr...@spu.edu> 于2022年8月31日周三 06:07写道:
Reply all
Reply to author
Forward
0 new messages