搜索
您的当前位置:首页正文

从Objective-C角度理解Golang面向对象编程

来源:二三娱乐

Golang里面没有类,而对象是使用struct模拟的,对于没接触C语言模拟对象属性的人来说比较难理解。所以拿Objective-C进行举例对比说明。
一个Golang对象:

type Human struct {
    name string
    age int
}

type Men interface {
    Say()
}

fun (h Human) Say() {
    fmt.Printf("Hi, i am %s, %s years old.\n", h.name, h.age)
}

对应的Objective-C类:

//.h文件
@interface human : NSObject
@property (copy, nonatomic) NString *name;
@property (assign, nonatomic) int *age;

- (void)say;
@end

//.m文件
@interface human ()
@end

@implementation human
- (void)say {
    NSLog(@""Hi, i am %@, %d years old.\n", self.name, self.age");
}
@end

Top