Yes, in Go language, the first letter of the interface is usually capitalized. This is done to: follow conventions; improve readability and stand out in the code; and distinguish between types and instances. Exceptions to the rule include embedded interfaces and test interfaces, whose first letter can be lowercase.
Does the first letter of Go language interface have to be capitalized?
In the Go language, an interface is a type that defines a set of methods. Normally, the first letter of an interface is uppercase. There are several reasons for doing this:
Exceptions to the rule:
In some cases, the first letter of an interface does not have to be capitalized:
Practical case:
The following example shows how to define an interface and the use of capitalizing its first letter:
// 定义一个名为 Shape 的接口 type Shape interface { Area() float64 } // 定义一个实现 Shape 接口的 Circle 类型 type Circle struct { Radius float64 } // 实现 Circle 类型的方法 Area() func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } // 使用 Shape 接口声明一个变量 var s Shape = Circle{10} // 调用 s 的 Area() 方法 fmt.Println(s.Area()) // 输出:314.1592653589793
In this example , the first letter of the Shape
interface is capitalized, indicating that it is an interface type. The Circle
type implements the Shape
interface, so it has an Area()
method. The variable s
is declared of type Shape
and assigned a Circle
instance. We can call the Area()
method on s
because the Circle
type implements this interface.
The above is the detailed content of Do the first letters of Go language interfaces have to be capitalized?. For more information, please follow other related articles on the PHP Chinese website!