Advertisement
Guest User

Untitled

a guest
Jan 30th, 2022
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.76 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type State struct {
  6.     X int
  7. }
  8.  
  9. type Command interface {
  10.     Execute(state *State)
  11. }
  12.  
  13. type MoveLeft struct {
  14.     Command
  15. }
  16.  
  17. func (c *MoveLeft) Execute(state *State) {
  18.     state.X -= 1
  19. }
  20.  
  21. type Executor interface {
  22.     Execute(command Command)
  23. }
  24.  
  25. type Dummy struct {
  26.     State State
  27.     Executor
  28. }
  29.  
  30. func (d *Dummy) Execute(command Command) {
  31.     command.Execute(&d.State)
  32. }
  33.  
  34. func main() {
  35.     foo := Dummy{State: State{X: 0}}
  36.     fmt.Println(foo.State) // {0}
  37.  
  38.     // Cannot use 'MoveLeft{}' (type MoveLeft) as the type CommandType does
  39.     // not implement 'Command' as the 'Execute' method has a pointer reciever
  40.     //foo.Execute(MoveLeft{})
  41.  
  42.     // но по ссылке все гуд
  43.     foo.Execute(&MoveLeft{})
  44.     fmt.Println(foo.State) // {-1}
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement