带导出字段的私人类型 [英] private type with exported fields

查看:84
本文介绍了带导出字段的私人类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在go教程的第2天有这个练习:

为什么使用导出字段的私有类型会很有用?



例如:

 包几何

类型点结构{
X,Y int;
名称字符串;

注意 point 是小写字母,因此不会导出,而字段X和Y是大写字母,因此是。在我看来,为了能够访问其中一个导出的字段,您必须能够写出类似的内容。

  pX 

但为了做到这一点,p必须有一个声明例如:

  var p geomitry.point; 

  p:= new(geomitry.point); 

然而这是不可能的(afaik),因为点的类型声明不被导出。 / p>

解决方案

但是你可以有一个公共构造函数,对吗?
$ b $如果你定义了一个 NewGeometryPoint func,那么你也许可以做到(没有针对编译器测试过)

  p:= NewGeometryPoint(640,480); 
fmt.Println(X:,p.X,Y:,p.Y);


In day 2 of the go tutorial there is this exercise:

Why may it be useful to have a private type with exported fields?

For example:

package geometry

type point struct {
    X, Y int;
    name string;
}

Notice that point is lowercase and thus not exported, whereas the fields X and Y are uppercase and thus are. It seems to me, that in order to have access to one of the exported fields, you would have to be able to write something like.

p.X

But in order for that to be possible, p would have to have a declaration like such:

var p geomitry.point;

or

p := new(geomitry.point);

This however is not possible (afaik), since the type declaration for point isn't exported.

解决方案

But you could have a public constructor, right?

So if you had a NewGeometryPoint func defined, then you maybe could do (haven't tested against the compiler)

p := NewGeometryPoint(640,480);
fmt.Println("X:",p.X, "Y:",p.Y);

这篇关于带导出字段的私人类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆