Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: document the behaviour of %p on slices #23291

Closed
nhooyr opened this issue Dec 31, 2017 · 3 comments
Closed

fmt: document the behaviour of %p on slices #23291

nhooyr opened this issue Dec 31, 2017 · 3 comments

Comments

@nhooyr
Copy link
Contributor

nhooyr commented Dec 31, 2017

I was surprised by the following program's output:

package main

import (
	"fmt"
)

func main() {
	foo := make([]int, 0, 1)
	fmt.Printf("same: %p\n", foo)

	foo = append(foo, 0)
	fmt.Printf("same: %p\n", foo)

	foo = append(foo, 0)
	fmt.Printf("different: %p\n", foo)
}

Example output:

same: 0xc420018060
same: 0xc420018060
different: 0xc420018070

I was expecting an error because there is no documentation regarding %p with slices in https://golang.org/pkg/fmt/ but it works fine.

I was surprised by the output as the printed address changed when the underlying array of the slice was modified. This is the expected behaviour because fmt is using the reflect package's Pointer() method on the slice, which will return the address of the first element of the slice. See

go/src/reflect/value.go

Lines 1267 to 1269 in 38c561c

// If v's Kind is Slice, the returned pointer is to the first
// element of the slice. If the slice is nil the returned value
// is 0. If the slice is empty but non-nil the return value is non-zero.

There should be some documentation regarding this behaviour because it is unexpected imo.

@ianlancetaylor ianlancetaylor added this to the Go1.11 milestone Jan 2, 2018
@martisch
Copy link
Contributor

martisch commented Jan 2, 2018

The valid reflect types for the verb %p are listed here:
https://github.com/golang/go/blob/master/src/fmt/print.go#L495
If CL with documentation for %p on slices is created it could be expanded to cover all possible types that are not already documented.

@gopherbot
Copy link

Change https://golang.org/cl/103516 mentions this issue: fmt: document the behaviour of %p on slices

@mewmew
Copy link
Contributor

mewmew commented Mar 29, 2018

PR #24600 seeks to address this issue, by documenting that %p on a slice prints the address of its first element (rather than the address of the slice descriptor).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants