Last active
January 5, 2020 00:36
-
-
Save nobishino/22a6944157a7ef188aada36d1d496f77 to your computer and use it in GitHub Desktop.
This file contains 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 | |
//1 | |
type Vertex struct { | |
X, Y int | |
} | |
//pointer receiver | |
func (v *Vertex) Plus() int { | |
return v.X + v.Y | |
} | |
func main() { | |
v := Vertex{3, 4} | |
fmt.Println(v.Plus()) //(*v).Plus()とやる必要がない | |
} | |
//2 errorを実装するときの話 | |
/* | |
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. | |
type error interface { | |
Error() string | |
} | |
*/ | |
//MyErrorでerror interfaceを実装 | |
type MyError struct { | |
Msg string | |
} | |
//pointer receiverでError()を実装 | |
func (m *MyError) Error() string { | |
return m.Msg | |
} | |
func f() error { | |
return &MyError{"ERRRR"} //MyErrorのポインタを返す必要がある | |
//もし return MyError{"ERRRR"}とするとコンパイルエラー | |
} | |
/* | |
次のようにvalue receiverでError()を実装した場合は、f()がpointerを返しても返さなくてもOKになる | |
func (m MyError) Error() string { | |
return m.Msg | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment