You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以下Go代码运行抛出nil指针引用panic,请问问题出在哪里?

问题原因

  • 你的MultiFunctionMachine结构体中的printer字段属于接口类型,你初始化multiMachine的时候没有给该字段赋值,它的默认值为nil,调用m.printer.Print(d)时触发空指针解引用panic。
  • 此外你只定义了Printer接口,没有任何结构体实现该接口的Print方法,就算给字段赋值了也没法执行实际打印逻辑。

修复方案

首先定义实现Printer接口的结构体,再初始化MultiFunctionMachine的时候给printer字段传入有效实例即可:

package main

import "fmt"

type Document struct{
    testString string
}

type Printer interface{
    Print(d *Document)
}

type Scanner interface{
    Scan(d *Document)
}

// 新增实现Printer接口的结构体
type EpsonPrinter struct{}
func (e *EpsonPrinter) Print(d *Document) {
    fmt.Println("打印内容:", d.testString)
}

type MultiFunctionMachine struct{
     printer Printer
     scanner Scanner    
}

func (m *MultiFunctionMachine)Print(d *Document){       
    m.printer.Print(d)
}

func main(){
    doc:= Document{"test"}      
    // 初始化时给printer字段赋值有效实例
    multiMachine:= MultiFunctionMachine{
        printer: &EpsonPrinter{},
    }
    multiMachine.Print(&doc)
}

运行后输出结果:

打印内容: test

内容的提问来源于stack exchange,提问作者DSL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 08:57:03