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

Golang中如何访问interface返回的[][]float32类型的单个元素值

Accessing Individual Elements from a TensorFlow Go Result (interface{} Type)

Hey there! The issue you're hitting is that result[0].Value() returns an interface{} type, and Go doesn’t let you directly index into an interface—you first need to type assert it to the underlying [][]float32 type you know it represents.

Here’s how to fix this step by step:

  1. First, capture the raw interface value from the tensor:

    rawPrediction := result[0].Value()
    
  2. Use a type assertion to convert it to a [][]float32. Always include the ok check to avoid panics if the type doesn’t match (this is good practice for safe code):

    prediction, ok := rawPrediction.([][]float32)
    if !ok {
        log.Fatalf("Expected [][]float32, got %T", rawPrediction)
    }
    
  3. Now you can safely access the individual elements just like you tried originally:

    fmt.Println("First element:", prediction[0][0]) // Prints 0
    fmt.Println("Second element:", prediction[0][1]) // Prints 1
    

Putting it all together with your original code (plus error handling you should include):

result, runErr := model.Session.Run(
    map[tf.Output]*tf.Tensor{
        model.Graph.Operation("x").Output(0): tensor,
    },
    []tf.Output{
        model.Graph.Operation("predict").Output(0),
    },
    nil,
)
if runErr != nil {
    log.Fatal(runErr) // Don't skip handling this error!
}

rawPrediction := result[0].Value()
prediction, ok := rawPrediction.([][]float32)
if !ok {
    log.Fatalf("Unexpected type for prediction: %T", rawPrediction)
}

fmt.Println(prediction[0][0]) // Outputs 0
fmt.Println(prediction[0][1]) // Outputs 1

Why your original attempt failed

When you tried result[0].Value()[0][0], Go couldn’t resolve the type of result[0].Value() at compile time—it’s just an interface{}, which the compiler treats as a generic "box" with unknown contents. It has no idea the underlying value is a 2D float32 array, so it won’t let you perform indexing operations until you assert the concrete type.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:19:43