Golang 打印一个类的对象
类的对象是什么
对象将键值对的数据存储在一起。有许多方法可以产生一个对象。本文将介绍其中一些方法。
在本文中,我们将使用两种不同的方法来在Go编程语言中打印类的对象。
方法1:使用结构体
在这种方法中,我们首先创建一些结构体,并在main()函数中创建对象。然后我们将属性存储到这些对象中,并将它们打印到屏幕上。可以通过以下步骤来实现。
步骤
- 步骤1 − 首先,我们需要导入fmt包。
-
步骤2 − 创建一个类并初始化一个新的结构类型,并在其中定义我们想要在类中定义的属性。在这个示例中,我们创建了两个结构体,一个名为student,另一个名为Animals。
-
步骤3 − Student类中定义了三个属性,即Id、Name和Fees,而Animals类中定义了一些属性,如species、color和price。
-
步骤4 − 调用main()函数。这是我们程序的起始点。
-
步骤5 − 从Student类中创建Student1、Student2和Student3对象,并为已初始化的键提供值。现在使用fmt.Println()函数将对象打印到屏幕上。
-
步骤6 − 类似地,从animals类创建两个对象animal1和animal2,并为其键提供值。使用fmt.Println()函数打印相应的对象到屏幕上。
示例
在本程序中,我们将编写一个Go语言程序,通过使用结构体打印一个类的对象
package main
import "fmt"
// Creating a structure named Student
type Student struct {
Id int
Name string
Fees int
}
// Creating a class named Animals
type Animals struct {
species string
color string
price int
}
func main() {
// Creating different objects from the Student class
student1 := Student{Id: 101, Name: "Kapil", Fees: 10000}
student2 := Student{Id: 102, Name: "Amit", Fees: 12000}
student3 := Student{Id: 103, Name: "Arun", Fees: 15000}
// Printing the objects created above on the screen
fmt.Println("Student's Information:")
fmt.Println("\nStudent1:", student1)
fmt.Println("\nStudent2:", student2)
fmt.Println("\nStudent3:", student3)
fmt.Println()
animal1 := Animals{species: "Dog", color: "white", price: 10000}
animal2 := Animals{species: "Cat", color: "Red", price: 1000}
fmt.Println("Animal's Information:")
fmt.Println(animal1)
fmt.Println(animal2)
}
输出
Student's Information:
Student1: {101 Kapil 10000}
Student2: {102 Amit 12000}
Student3: {103 Arun 15000}
Animal's Information:
{Dog white 10000}
{Cat Red 1000}
方法2:使用new关键字
在这种方法中,我们创建并定义一个结构体,然后通过new关键字创建该结构体的对象。
步骤
- 步骤1 - 导入fmt包。
-
步骤2 - 接下来,我们创建一个名为Employee的结构体,并在其中定义像name、age、salary等键。
-
步骤3 - 然后我们调用main()函数。
-
步骤4 - 使用new关键字创建名为newEmp的Employee类对象,并将值作为逗号分隔的值传递给键。
-
步骤5 - 现在,我们的newEmp对象包含了所有必要的数据,我们可以使用fmt.Println()函数将其打印在屏幕上。
-
步骤6 - 要访问对象的任何属性,我们需要在指定对象名称后使用“.”符号,然后是要访问的属性。
注意 - 在创建对象时,如果我们没有为结构体中声明的任何属性提供值,则会选择一些默认值。下面是一些典型的值。
- 默认情况下,字符串值为””时为空字符串。
-
整数数值的输入值默认为0。
-
布尔值默认为false。
示例
在这个示例中,我们创建了一个Go语言程序,使用new关键字打印类的对象。
package main
import "fmt"
// Defining a structure named Employee
type Employee struct {
Name string
Age int
Designation string
Salary int
}
func main() {
// creating an empty object named newEmp.
var newEmp = new(Employee)
newEmp.Name = "Ram"
newEmp.Age = 30
newEmp.Designation = "Senior Developer"
newEmp.Salary = 50000
fmt.Println("Printing the employee object")
fmt.Println(newEmp)
fmt.Println()
fmt.Println("The age of employee is:", newEmp.Age)
fmt.Println("The name of employee is:", newEmp.Name)
fmt.Println("The default values for salary is:",
newEmp.Salary)
}
输出
Printing the employee object
&{Ram 30 Senior Developer 50000}
The age of employee is: 30
The name of employee is: Ram
The default values for salary is: 50000
结论
我们成功地编译并执行了一个Go语言程序,将类的对象以及示例打印在屏幕上。在这里我们创建了两个示例。在第一个示例中,我们使用了等号运算符来创建对象并存储数据,而在第二个示例中,我们使用了new关键字来创建对象。