2014-09-05 01:13



This code has some objects representing a user and the admin who created that user. It's a trimmed down version of some code submitted to us by an applicant. The code is broken and deletes the admin when you try to delete the user (as demonstrated by main). Why does u.Delete call the admin's delete instead of the user's delete?

package admin
import "fmt"
type Admin struct {}
func (Admin) Delete() {
    fmt.Println("deleting admin")

package user
import (
type User struct {*admin.Admin}
func (*User) D
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dpntq48842 dpntq48842 7年前

    In your sample code the letter e in User's Delete method is not of the same encoding as the letter e in Admin's Delete method. Since Go supports utf8 this is not an error but it is a different method. Fix the e in User's Delete method and all should work as expected.

    点赞 评论 复制链接分享
  • duan19805 duan19805 7年前

    because the method delete on the user is defined for *User not for User, while Admin's Delete is defined for the non pointer Admin. User embeds Admin, so it inherits func (Admin) Delete() method.

    try using the pointer to user (notice the &)

    func main() {
        u := &user.User{&admin.Admin{}}
    点赞 评论 复制链接分享