Golang 显示访问修饰符的使用
在Go编程语言中,有两种类型的访问修饰符,即导出的和未导出的。在指定它们的包中导出的标识符被称为导出的标识符。它们总是以大写字母开头。这些标识符只在定义它们的包中有效。未从任何包导出的标识符被称为小写形式的未导出的标识符。
语法
func len(v Type) int
len()函数用于获取任何参数的长度。它接受一个参数作为数据类型变量,我们希望找到其长度,并返回整数值,该值为变量的长度。
func ToUpper(str string) string
ToUpper() 函数位于strings包中,用于将给定的字符串转换为大写。该函数接受给定的字符串作为参数,并在将其转换为大写后返回最终的字符串。
方法1: 使用导出的标识符
现在我们来考虑一个示例,通过使用导出函数的封装概念,将一个字符串数组转换为大写。
步骤
- 步骤1 – 首先,我们需要导入所需的包,如fmt和strings。
- 步骤2 – 然后,调用main()函数。
- 步骤3 – 初始化一个字符串数组并将字符串值存储在其中。然后,将数组打印在屏幕上。
- 步骤4 – 现在,启动一个for循环来对数组进行索引,并使用string.ToUpper()函数将数组的每个元素转换为大写,并将结果数组存储在results中。
- 步骤5 – 现在,使用fmt.Println()函数将结果打印在屏幕上。
示例
以下示例将说明如何使用导出的标识符来访问go编程语言中的修饰符。
package main
import (
"fmt"
"strings"
)
func main() {
// creating an array of strings and assigning values to it
arr := []string{"apple", "banana", "fruits"}
fmt.Println("Successfully converted array of strings to upper case using Exported method ToUpper() defined in strings package")
fmt.Println("The resultant string is:")
for x := 0; x < len(arr); x++ {
// calling the exported method ToUpper()
results := strings.ToUpper(arr[x])
fmt.Println(results)
}
}
输出
Successfully converted array of strings to upper case using Exported method ToUpper() defined in strings package
The resultant string is:
APPLE
BANANA
FRUITS
方法2:使用未导出的标识符
现在我们来看一个示例,通过封装的概念使用未导出的函数,我们将尝试找到整数数组的总和。
步骤
- 步骤1 - 首先,我们需要导入fmt包。
-
步骤2 - 初始化并定义一个名为addition()的方法来计算整数数组的总和。该函数接受一个整数数组作为参数,并计算其总和。
-
步骤3 - 它使用for循环遍历数组的每个元素,找到它们的总和并存储在一个新声明的变量s中。然后函数返回结果。
-
步骤4 - 现在,调用main()函数。
-
步骤5 - 初始化一个整数数组并存储值。然后使用fmt.Println()函数将数组打印在屏幕上。
-
步骤6 - 现在通过将数组作为参数传递给addition()函数来调用它。注意,在调用addition函数时,第一个字母是小写的,这表示该函数是未导出的,并且在main函数中定义。
-
步骤7 - 现在,将结果存储在一个不同的变量中,并将其打印在屏幕上。
示例
以下示例将解释如何使用未导出的标识符来访问Go编程语言中的修饰符。
package main
import "fmt"
func addition(val []int) int {
s := 0
for x := range val {
s += val[x]
}
return s
}
// Calling the main function
func main() {
// defining an array of integers and storing values in it
arr := []int{50, 29, 36, 55, 87, 95}
fmt.Println("The given array of integers is:", arr)
result := addition(arr)
fmt.Println()
fmt.Println("Succesfully found the sum of array of integers using UnExported method addition()")
fmt.Println("The resultant sum is:")
fmt.Println(result)
}
输出
The given array of integers is: [50 29 36 55 87 95]
Succesfully found the sum of array of integers using UnExported method addition()
The resultant sum is:
352
结论
我们已成功编译并执行了一个Go语言程序,用于展示访问修饰符的用法,并附带了示例。在这里,我们使用了Go编程语言中的两种访问修饰符,即导出和未导出。