Skip to content

Bypassing unexported field protection using interfaces #1402

@gopherbot

Description

@gopherbot

by ben.leslie:

It is possible to bypass the protection against copying of protected fields in
unprotected types.

See thread: http://groups.google.com/group/golang-nuts/browse_frm/thread/10f333af7a3299e0

Example code:

<<<< ifhack.go 
package ifhack 
import "fmt" 
type Hack struct { 
        private int 
} 

func (h Hack) String() string { 
        return fmt.Sprintf("hack:%d", h.private) 
} 

<<<< ifhackCaller.go 
package main 
import "fmt" 
import "ifhack" 
func main() { 
        var hack ifhack.Hack 
        var hackptr *ifhack.Hack 
        var s fmt.Stringer 
        s = &hack 
        hackptr = &hack 
        fmt.Printf("%s\n", hack.String()) // implicit assignment of unexported field 'private' of ifhack.Hack in method receiver 
        fmt.Printf("%s\n", (&hack).String()) // implicit assignment of unexported field 'private' of ifhack.Hack in method receiver 
        fmt.Printf("%s\n", s.String()) 
        fmt.Printf("%s\n", hackptr.String()) // implicit assignment of unexported field 'private' of ifhack.Hack in method receiver 
        fmt.Printf("%s\n", hack) // implicit assignment of unexported field 'private' of ifhack.Hack in function argument 
        fmt.Printf("%s\n", (&hack)) 
        fmt.Printf("%s\n", s) 
        fmt.Printf("%s\n", hackptr) 
} 


Expected behaviour is that it should not be possible to call the String() method
indirectly via the Stringer interface.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions