Closed sajjanjyothi closed 1 year ago
There is no need for a language or library change; it's literally a one-liner, even in gofmt'ed Go. Just put this one-line func in your tests.
func ptr(s string) *string { return &s }
https://go.dev/play/p/D60yCWbOuAN
Bonus: if you do it my way, the call site is much shorter and requires no external module.
FWIW we tend to write a generic helper in some packages, like:
func addr[T any](t T) *T { return &t }
It is relatively common but I'm not even sure where this would belong in std, other than perhaps builtin, if not the language itself in some other form.
@mvdan then maybe new
should accept constants and literals ?
see #45624
also #61082
emp: = Employee{
Name: &[]string{"hello"}[0],
}
I think the generic implementation would be an ideal solution func pointer[T any](v T) *T { return &v }
if we could accommodate in language itself as suggested part of std lib, would be easy for almost all go devs :)
Closing as a dup of #61082. Thanks.
When we want to pass a string pointer to a struct member each time we have to create a separate variable and pass the address of that to the member variable, Which is a pain. This wrapper function will ease all those efforts. Eg: type Employee struct{ Name *string }
To pass a variable in testing , we have to testName := "hello"
emp := Employee{ Name: &testName, }
I have added a pull request to address this as https://github.com/golang/go/pull/63299 With this function it is
emp: = Employee{ Name: strings.StringPointerFrom("hello") }
It is really helpful when we are using table tests.