[GODRIVER-2060] Golang decode doesn't work with interfaces Created: 24/Jun/21  Updated: 27/Oct/23  Resolved: 27/Aug/21

Status: Closed
Project: Go Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Unknown
Reporter: Sean Teeling Assignee: Matt Dale
Resolution: Gone away Votes: 0
Labels: post-5.0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When unmarshaling objects in Go, you can't pass in an interface, however it works when unmarshaling json.

 

```

type X interface {}

type Y struct {}

 

var z X

z = &Y{}

 

d.Decode(z) // works in json, not with bson.

```

 

This is severely limiting for what we can do with the API



 Comments   
Comment by Backlog - Core Eng Program Management Team [ 27/Aug/21 ]

There hasn't been any recent activity on this ticket, so we're resolving it. Thanks for reaching out! Please feel free to comment on this if you're able to provide more information.

Comment by Matt Dale [ 12/Aug/21 ]

Hey teeling.sean@gmail.com, thanks for your patience! I just got around to trying to reproduce the failure to decode BSON to an interface variable, but I'm unable to reproduce any failure.

Here's the code I used to try to reproduce the failure. Both functions decode and print the same Y struct. Note that I'm using Go driver v1.7.1.

type X interface{}
 
type Y struct {
	A int
	B string
}
 
func JSON() {
	var z X
	z = &Y{}
 
	d := json.NewDecoder(strings.NewReader(`{"A": 3, "B": "three"}`))
	err := d.Decode(z)
	if err != nil {
		panic(err)
	}
	fmt.Println(z)
}
 
func BSON() {
	b, err := bson.Marshal(Y{A: 3, B: "three"})
	if err != nil {
		panic(err)
	}
 
	var z X
	z = &Y{}
 
	d, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(b))
	if err != nil {
		panic(err)
	}
	err = d.Decode(z)
	if err != nil {
		panic(err)
	}
	fmt.Println(z)
}
 
func main() {
	JSON()
	BSON()
}

Can you provide the complete code sample that you're trying to make work, including any calls to bson.NewDecoder()? In your code, does d.Decode() return any errors? Also, what version of the Go driver are you using?

Thanks,
Matt

Comment by Kevin Albertson [ 28/Jun/21 ]

Hello teeling.sean@gmail.com, thank you for the report! We will further investigate this after we have completed high priority work for upcoming server support. Thank you for your patience.

Generated at Thu Feb 08 08:37:44 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.