go make example
package main
import (
"fmt"
)
// Define a struct named Person with fields Name and Age
type Person struct {
Name string
Age int
}
// Define a method Speak for the Person struct
func (p Person) Speak() {
fmt.Printf("Hello, my name is %s and I am %d years old\n", p.Name, p.Age)
}
func main() {
// Create an instance of the Person struct
person := Person{
Name: "John",
Age: 30,
}
// Call the Speak method on the person object
person.Speak()
}
Explanation:
Define a package named "main" to indicate that this Go file will serve as an executable program.
Import the "fmt" package, which provides functions for formatting and printing output.
Define a struct named "Person" with two fields: "Name" of type string and "Age" of type int.
Define a method named "Speak" for the "Person" struct. This method prints a formatted message using the "fmt.Printf" function, introducing the person's name and age.
In the "main" function, create an instance of the "Person" struct named "person" with the values "Name: John" and "Age: 30".
Call the "Speak" method on the "person" object to print a message introducing the person.
Note: This example demonstrates the basic structure of a Go program, including package declaration, importing packages, defining a struct, creating an instance of the struct, and calling a method on the struct instance.