On Monday, 8 December 2014 12:53:49 UTC+11, hus...@163.com wrote:
Why Golang decides the "Sting()" argument is actually a copy but not the reference?

package main

import "fmt"

type Student struct {

name string

age int


func (s Student) String() string {

fmt.Printf("%p\n", &s) //It shows that the s is actually a copy, if the function is declared as "func (s *Stude///nt) String() string" then it will not be called

return fmt.Sprintf("name is %s\n", s.name)


You have declared the String method to be on the Student value type, not
*Student. Method calls in go _ALWAYS_ copy the receiver, they are in effect
func String(s Student) string. This is why the address of s differs from
the caller's.

func main() {

s := Student{name: "charlie", age: 18}

fmt.Printf("%p\n", &s)






name is charlie

as it shows, the argument passing to String() is actual a copy of the object, is that a waste of efficiency?
No, consider this func Print(s string) { .. }

You can see from above this function takes exactly the same number of
arguments, 1, a two word structure for the string header.

You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 5 of 6 | next ›
Discussion Overview
groupgolang-nuts @
postedDec 8, '14 at 1:53a
activeDec 8, '14 at 2:19p



site design / logo © 2021 Grokbase