Table of Contents
Define the Struct and Method
Use Pointer Receivers When You Need to Modify the Instance
Call Methods on Embedded Structs
Keep It Simple: No Need for Getters or Setters
Home Backend Development Golang How do I call a method on a struct instance in Go?

How do I call a method on a struct instance in Go?

Jun 24, 2025 pm 03:17 PM
go Structural method

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func (r Rectangle) Area() int, and it is called directly through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func (r *Rectangle) SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be promoted and can be called directly through the outer structure; 4. Go does not need to force getter/setter, and fields can be accessed directly unless logical control is required. These mechanisms make method calls concise and flexible.

How do I call a method on a struct instance in Go?

In Go, calling a method on a struct instance is straightforward — you use dot notation, just like accessing fields. The key is understanding how methods are defined with receivers tied to specific types.

Define the Struct and Method

First, define a struct type, then declare a method with a receiver of that type:

 type Rectangle struct {
    Width, Height int
}

func (r Rectangle) Area() int {
    return r.Width * r.Height
}

Here, Area is a method on Rectangle . The (r Rectangle) part means it's a value receiver — the method gets a copy of the Rectangle instance it's called on.

To call it:

 rect := Rectangle{Width: 3, Height: 4}
fmt.Println(rect.Area()) // Output: 12

This works because Go automatically handles pointer vs. value receivers for you — more on that below.


Use Pointer Receivers When You Need to Modify the Instance

If your method needs to modify the struct, use a pointer receiver:

 func (r *Rectangle) SetWidth(newWidth int) {
    r.Width = newWidth
}

Then call it like this:

 rect := &Rectangle{Width: 3, Height: 4}
rect.SetWidth(5)
fmt.Println(rect.Width) // Output: 5

A few things to note:

  • If you have a pointer to a struct, Go lets you call both value and pointer methods.
  • If you have a value, you can only call value methods unless Go automatically takes its address.

So if you write:

 rectVal := Rectangle{3, 4}
rectVal.SetWidth(5) // still works!

Go will automatically convert rectVal to a pointer when calling SetWidth , so you don't have to worry about matching types in most cases.


Call Methods on Embedded Structs

Go supports embedding structs inside other structs, and their methods are promoted:

 type Inner struct {
    Value int
}

func (i Inner) PrintValue() {
    fmt.Println(i.Value)
}

type Outer struct {
    Inner // embedded
}

Now you can call the method directly on the outer struct:

 o := Outer{Inner{Value: 10}}
o.PrintValue() // Output: 10

This avoids having to write o.Inner.PrintValue() every time.


Keep It Simple: No Need for Getters or Setters

Unlike some languages, Go doesn't require getters and setters. Since all fields are public if capitalized, you can access them directly unless you need logic around setting a value.

For example:

 // Just assign directly
rect.Width = 6

// Only use a method if validation is needed
func (r *Rectangle) SetWidthSafe(w int) {
    if w < 0 {
        panic("width must be non-negative")
    }
    r.Width = w
}

Calling this is no different than any other method:

 rect := &Rectangle{}
rect.SetWidthSafe(5)

Calling a method on a struct in Go is simple once you understand receivers. Whether you're working with value or pointer receivers, embedded types, or direct field access, Go gives you flexibility without extra boilerplate.

Basically that's it.

The above is the detailed content of How do I call a method on a struct instance in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
How to get the current time in Go How to get the current time in Go Aug 06, 2025 am 11:28 AM

Usetime.Now()togetthecurrentlocaltimeasatime.Timeobject;2.FormatthetimeusingtheFormatmethodwithlayoutslike"2006-01-0215:04:05";3.GetUTCtimebycallingUTC()ontheresultoftime.Now();4.Extractcomponentslikeyear,month,dayusingmethodssuchasYear(),M

How do you cross-compile a Go application? How do you cross-compile a Go application? Aug 06, 2025 am 05:52 AM

Cross-compilingaGoapplicationisstraightforwardusingbuilt-insupportviaGOOSandGOARCH.1.SetGOOSforthetargetoperatingsystem(e.g.,linux,windows,darwin).2.SetGOARCHforthetargetarchitecture(e.g.,amd64,arm64).3.Rungobuildwiththesevariables,suchasGOOS=linuxGO

How to create and use custom error types in Go How to create and use custom error types in Go Aug 11, 2025 pm 11:08 PM

In Go, creating and using custom error types can improve the expressiveness and debugability of error handling. The answer is to create a custom error by defining a structure that implements the Error() method. For example, ValidationError contains Field and Message fields and returns formatted error information. The error can then be returned in the function, detecting specific error types through type assertions or errors.As to execute different logic. You can also add behavioral methods such as IsCritical to custom errors, which are suitable for scenarios that require structured data, differentiated processing, library export or API integration. In simple cases, errors.New, and predefined errors such as ErrNotFound can be used for comparable

How to Handle Panics and Recover in Go How to Handle Panics and Recover in Go Aug 06, 2025 pm 02:08 PM

The recover function must be called in defer to capture panic; 2. Use recovery in long-running programs such as goroutine or server to prevent the entire program from crashing; 3. Recover should not be abused, only used when it is handled, to avoid replacing normal error handling; 4. Best practices include recording panic information, using debug.Stack() to obtain stack traces and recovering at an appropriate level. Recover is only valid within defer and should be used for debugging with logs. Potential bugs cannot be ignored. In the end, the code should be designed by returning error rather than panic.

How to implement a generic LRU cache in Go How to implement a generic LRU cache in Go Aug 18, 2025 am 08:31 AM

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

How do you handle signals in a Go application? How do you handle signals in a Go application? Aug 11, 2025 pm 08:01 PM

The correct way to process signals in Go applications is to use the os/signal package to monitor the signal and perform elegant shutdown. 1. Use signal.Notify to send SIGINT, SIGTERM and other signals to the channel; 2. Run the main service in goroutine and block the waiting signal; 3. After receiving the signal, perform elegant shutdown with timeout through context.WithTimeout; 4. Clean up resources such as closing database connections and stopping background goroutine; 5. Use signal.Reset to restore the default signal behavior when necessary to ensure that the program can be reliably terminated in Kubernetes and other environments.

How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

How to use path/filepath for cross-platform path manipulation in Go How to use path/filepath for cross-platform path manipulation in Go Aug 08, 2025 pm 05:29 PM

Usefilepath.Join()tosafelyconstructpathswithcorrectOS-specificseparators.2.Usefilepath.Clean()toremoveredundantelementslike".."and".".3.Usefilepath.Split()toseparatedirectoryandfilecomponents.4.Usefilepath.Dir(),filepath.Base(),an

See all articles