dongtan7418
dongtan7418
2016-08-17 02:57

Iris框架在实现指针接收器和值接收器方面的差异

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

I am studying Iris framework recently. I encountered a question when I was implementing the Handler. Like following:

package controller

import "github.com/kataras/iris"    

type Pages struct{
}

func (p *Pages) Serve(c *iris.Context) {
}

In order to use this controller, I implemented the following entry script:

package main

import (
     "github.com/kataras/iris"
     "web/controller"
)

func main(){
      ctrl := controller.Pages{}
      iris.Handle("GET", "/", ctrl)
      iris.Listen(":8080")
}

But when I compiled the code, I got the following error message:

cannot use ctrl (type controllers.Pages) as type iris.Handler in argument to iris.Handle:
controllers.Pages does not implement iris.Handler (Serve method has pointer receiver)

After I changed the declaration to:

ctrl := &controller.Pages{}

Then the compiler passed with no complaint.

The question is: I thought the following statements are equal, since the GO compiler will do the conversion under the table:

type Pages struct {
}

func (p *Pages) goWithPointer() {
    fmt.Println("goWithPointer")
}

func (p Pages) goWithValue() {
    fmt.Println("goWithValue")
}

func main() {
    p1 := Pages{}
    p2 := &Pages{}

    p1.goWithPointer()
    p1.goWithValue()

    p2.goWithPointer()
    p2.goWithValue()
}

Why can't I use ctrl := controller.Pages{} as the parameter to iris.Handle(), instead of ctrl := &controller.Pages{} as the parameter to iris.Handle()?

Thank you for your time and sharing.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐