golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.83k stars 17.65k forks source link

proposal: strings: Create a string pointer from string constant #63309

Closed sajjanjyothi closed 1 year ago

sajjanjyothi commented 1 year ago

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.

robpike commented 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.

mvdan commented 1 year ago

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.

Jorropo commented 1 year ago

@mvdan then maybe new should accept constants and literals ?

seankhliao commented 1 year ago

see #45624

seankhliao commented 1 year ago

also #61082

zigo101 commented 1 year ago
emp: = Employee{
   Name: &[]string{"hello"}[0],
}
sajjanjyothi commented 1 year ago

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 :)

ianlancetaylor commented 1 year ago

Closing as a dup of #61082. Thanks.