How to use CanConvert() of reflect.Value - go

I have a reflect.Value type of data and I want to check if the value can be convert to uint or not.
this is just an example hope you guys get the idea
var myVal = new(reflect.Value)
if myVal.CanConvert(uint) { // this doesn't work
// do stuf...
}
I dont know what I have to pass as the argument of CanConvert()

The argument to the CanConvert method is a reflect.Type. Use the reflect.TypeOf function to get a reflect.Type from a value of the type.
if myVal.CanConvert(reflect.TypeOf(uint(0)) {
// do stuff...
}

Related

How do I extend a widget.Button so that it has a new method ID in fyne?

I did this but it doesn't work
type buttonWithID struct {
widget.ListItemID
}
func newButtonWithID(button widget.Button) *buttonWithID {
newButton := &buttonWithID{}
newButton.ExtendBaseWidget(newButton)
newButton.ListItemID = 0
return newButton
}
and it returns this error:
newButton.ExtendBaseWidget undefined (type *buttonWithID has no field or method ExtendBaseWidget)
If you want to extend Button then your struct must embed the widget.Button type. Extra fields would be added below that.
See the tutorial at https://developer.fyne.io/tutorial/extending-widgets

How to omit some parameters of structure Gin gonic

I have big structure with more than 50 params
type Application struct {
Id int64 `json:"id"`
FullName string `json:"fullName,omitempty"`
ActualAddress string `json:"actualAddress,omitempty"`
.....
}
I use gin-gonic and when I return application I need to omit some params I've created a function which makes empty some params (playLink) and then gin returns me correct json (without unnecessary values). I heard that reflection isn't fast operation so in our case we can use a lot of ugly if-else or switch-cases. Is there any other solutions faster than reflecting and more beautiful than if-elses?
The thing is that structure params have non-empty values, so they wont by omitted by gin. That's why I've created function to make some params empty before return
The thing is, if you only want to zero a few fields, it's more readable to do it without a function, e.g.
app := Application{}
app.FullName, app.ActualAddress = "", ""
If you want to create a function for it, at least use variadic parameter, so it's easier to call it:
func zeroFields(application *Application, fields ...string) {
// ...
}
So then calling it:
zeroFields(&app, "FullName", "ActualAddress")
Yes, this will have to use reflection, so it's slower than it could be, and error prone (mistyped names can only be detected at runtime). If you want to avoid using reflection, pass the address of the fields:
func zeroFields(ps ...*string) {
for _, p := range ps {
*p = ""
}
}
This way you have compile-time guarantee that you type field names correctly, and that they have string type.
Calling it:
zeroFields(&application.FullName, &application.ActualAddress)
Try it on the Go Playground.
If I understand correctly: you want to return some values from your struct but not all of them? Perhaps a nested struct?
type Application struct {
ID struct {
ID int64 `json:"id"`
} `json:"id"`
Person struct {
Fullname string `json:"Fullname"
} `json:"person"
}
That should let you filter out the fields you want to use.

Initializing structures dynamically

I have a couple of structures, like:
type SomeObject struct {
sample int
}
I want to fill the sample variable based on what I get in the request body. To do this, I want to create a function, pass request body as a string to it, create an empty structure inside, fill the structure with data, return it, and replace chosen structure with this.
How do I do this? What do I return from the function? Is there a way to do this?
If you're dealing with multiple types then you should make your method return an interface{}. For all of the applicable types, create a convenience method like;
func NewSomeObject(reqBody string) *SomeObject {
return &SomeObject{sample:reqBody}
}
Which takes a string and returns a new instance of the type with that field set to whatever was passed in. Your question is missing information about how you determine which type should be instantiated but assuming you have a few, you'll likely need an if/else or a switch in the method which receives the request body so to give a very vague example it would be something like;
func ProcessRequest(reqBody string) interface{} {
if someCondition {
return NewSomeObject(reqBody)
} else if otherCondition {
return NewSomeOtherObject(reqBody)
} // potentially several other statements like this
return nil // catch all, if no conditions match
}
How about
func foo (s *SomeObject) {
s.sample = 123
}
or
func (s *SomeObject) foo() {
s.sample = 123
}

GO Multiple Pointers

I'm trying to create a function that receives multiple types of struct and add those pointer values to another function.
Example:
type Model1 struct {
Name string
}
type Model2 struct {
Type bool
}
func MyFunc(value ...interface{}) {
OtherFunc(value...)
}
func main() {
MyFunc( new(Model), new(Mode2) );
}
The problem is that OtherFunc only allow &value, &value, etc as parameter. Have some way to pass those values like OtherFunc(&value...)?
I'm not sure this will solve your problem entirely however, the exact thing you requested is a feature in the language. You just have to use composite-literal syntax for instantiation instead of new. So you could do this to pass pointers; MyFunc( &Model{}, &Mode2{} )
Thing is, you're still going to be dealing with an interface{} within MyFunc so I'm not sure that will just be able to call OtherFunc without some unboxing (would probably be a type assertion if you want to get technical).

Golang, call method from struct without variable

Is it possible to call method from struct without variable with this struct type?
//models.go
type MyStruct struct {
id int
name string
}
func (s MyStruct) GetSomeAdditionalData() string {
return "additional data string"
}
//app.go
func main() {
fmt.Println(models.MyStruct.GetSomeAdditionalData()) // not works
var variable models.MyStruct
fmt.Println(variable.GetSomeAdditionalData()) // it worked
}
Or maybe Go have other method to add some data for struct?
Or maybe I select wrong way to do it? :)
You can use a struct literal or a nil pointer.
MyStruct{}.GetSomeAdditionalData()
(*MyStruct)(nil).GetSomeAdditionalData()
To say you can. MyStruct.GetSomeAdditionalData() is called method expression and you must provide first argument of type MyStruct to that call. Argument can be anonymous composite literal MyStruct.GetSomeAdditionalData(MyStruct{}).
Here is working example https://play.golang.org/p/Wc_DjqnpLC . But all that looks not very sensible.
You can define a package function (without any receiver).
It differs from a method, as a method needs a receiver.
func GetSomeAdditionalData() string {
return "additional data string"
}
Which you can call directly, without any instance of the struct MyStruct needed (since you don't need any of MyStruct data anyway):
func main() {
fmt.Println(models.GetSomeAdditionalData())
fmt.Println(GetSomeAdditionalData())
(the second form works if you are in the package models already)

Resources