First of all, let’s see in which case we need this process.
A sample need scenario;
type MyStruct struct {
Text *string
}
Let’s have a struct
as above. We have a data that is parse to this model and let’s assume that the Text
field is filled after parse. In this case, it will be enough to use a suitable data for our model.
But if we wanted to fill the Text
field of the model we created when we had no data to parse, what should we do?
In fact, the best way to fulfill such a request, if it were supported by Go, would be as follows.
a := MyStruct{
Text: &"text",
}
// or
a := MyStruct{
Text: &string("text"),
}
However, since the method of giving the address of the string value with &"text"
is not supported, we have to resort to other methods.
Unfortunately the new
function can’t help either, because the new
function only creates a zero-valued variable and return its address. Therefore we cannot assign the value we set at once.
1. By Creating Helper Variable
We can create a helper variable to send the address to the Text
field.
text := "text"
a := MyStruct{
Text: &text,
}
2. By Creating Helper Function
We can create a helper function to send the address to the Text
field.
func Ptr(v string) *string{
return &v
}
.
.
.
a := MyStruct{
Text: Ptr("text"),
}
3. By Creating Helper Function With Generics
Actually best effective method is this method. Because it’s more readable and reusable method.
func Ptr[T any](v T) *T {
return &v
}
.
.
.
a := MyStruct{
Text: Ptr("text"),
}
Instead of *string
If we have a *int64
type field, we have to specify number as int64
. Because default decimal number type is int
. Thus we can not send parameter directly as Ptr(123)
. We can specify the type of the parameter in 2 different ways.
// first way
Ptr(int64(123))
// or second way
Ptr[int64](123)
4. By Using Slice
Another simple method that we can apply by using slice.
a := MyStruct{
Text: &[]string{"text"}[0],
}
But it is not a very readable writing style.
5. By Using One-liner Anon Function
a := MyStruct{
Text: func(v string) *string { return &v }("text"),
}
// or
a := MyStruct{
Text: func() *string { v := "text"; return &v }(),
}
This method also seems very complicated
Thank you for reading, I hope you enjoyed it
Top comments (0)