这个out对象是怎么实现xx接口的?

    package main

import (
    "io"
    "os"
)

// var (
//  kernel32DLL                 = syscall.NewLazyDLL("kernel32.dll")
//  setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute")
// )

type xx interface {
    Fd() uintptr
}

// type LogBackend struct {
//     Logger *log.Logger
// }

func main() {
    // NewLogBackend(os.Stdout, "", 0)
    test(os.Stdout)
}

func test(out io.Writer) {
    if _, ok := out.(xx); ok {
        println("get in ")
    }
}

out是怎么实现xx接口的,运行时进入了打印
(如果修改xx接口的Fd的名称 或者返回值则没有实现)

阅读 2.7k
1 个回答

传入的并不是单纯的writer对象,而是实现了writer对象功能的file对象。

其实这里有两个问题。

1.传入的参数需要实现Write接口(Writer的接口),才能保证编译通过
2.传入的参数需要实现Fd接口(xx对象所有的接口),才能保证ok=true

你运气好,File 对象(os.Stdout之类的)是实现了两个接口的。

type Writer interface {
    Write(p []byte) (n int, err error)
}
type File
func Create(name string) (*File, error)
func NewFile(fd uintptr, name string) *File
func Open(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)
func Pipe() (r *File, w *File, err error)
func (f *File) Chdir() error
func (f *File) Chmod(mode FileMode) error
func (f *File) Chown(uid, gid int) error
func (f *File) Close() error
func (f *File) Fd() uintptr
func (f *File) Name() string
func (f *File) Read(b []byte) (n int, err error)
func (f *File) ReadAt(b []byte, off int64) (n int, err error)
func (f *File) Readdir(n int) ([]FileInfo, error)
func (f *File) Readdirnames(n int) (names []string, err error)
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
func (f *File) Stat() (FileInfo, error)
func (f *File) Sync() error
func (f *File) Truncate(size int64) error
func (f *File) Write(b []byte) (n int, err error)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
func (f *File) WriteString(s string) (n int, err error)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题