Last active
April 18, 2022 06:15
-
-
Save jqjk/15f57a93c69aa3648ae4714fc42b5ba6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"reflect" | |
) | |
var ErrNotPointerToString = errors.New("Not a pointer to a string") | |
func main() { | |
var s string | |
err := setString(&s, "hoge") | |
fmt.Println(s, err == nil) // hoge true | |
var n int | |
err = setString(&n, "hoge") | |
fmt.Println(n, err == nil) // 0 false | |
} | |
func setString(s interface{}, value string) error { | |
v := reflect.ValueOf(s) | |
if v.Kind() == reflect.Ptr && | |
v.Elem().Kind() == reflect.String { | |
v.Elem().Set(reflect.ValueOf(value)) | |
return nil | |
} | |
return ErrNotPointerToString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment