As far as I know, maybe it's wrong, there's no way to extend functions or interfaces in Golang, created by other packages, much less in this case.
First, you need to set the imports
os
, but this will not solve the problem.
func (system os) Sudo() bool {
return system.Getenv("USER") == "root"
}
You actually expect os
to be a struct / interface, which in fact it is not. os
is a package.
In your case what you can do is create a new folder, for example "systemOS" and then declare "package systemOS", for example:
package systemOS
import "os"
func Sudo() bool {
return system.Getenv("USER") == "root"
}
Now you could call in your main, as long as you give the import in systemOS
newly created:
func main() {
if !systemOS.Sudo() {
fmt.Println("You have no permission to run as non-root user. Use sudo")
os.Exit(1)
}
}
In other cases, you can create a "synonym" (an alias) for another type. For example, it will be easier to use os/user
that contains a struct of user.User
.
package main
import (
"fmt"
"os/user"
)
type X user.User
func (u X) IsInkeliz() bool {
return u.Name == "Inkeliz"
}
func main() {
acc, err := user.Current()
if err != nil {
panic("")
}
if !X(*acc).IsInkeliz() {
fmt.Println("Você não é Inkeliz")
}
}
The X
is a type that is the same as user.User
. Then I convert X(*acc)
and I can access the IsInkeliz()
I created, inside the function I also get the .Name
that is of the original struct (of the user.User).
Another way to do this would be to create a Struct:
type X struct {
y *user.User
}
Then put acc
inside it and could access y.Name
.
However, in all cases you will be creating a new type. I do not know of any way to "extend" the type established by another package without having to create a new type.