首页 > 解决方案 > 语句末尾的意外 int

问题描述

我在这段 Go 代码上有点挣扎。我一直在到处寻找,但无法理解它有什么问题。

错误消息是:语法错误:语句末尾的意外 int

对于底部附近的那条线:func (TOHLCV TOHLCVs) Len() int {

对于第二行到最后一行代码,我也有此错误消息:

syntax error: non-declaration statement outside function body

如果2个错误相关

package main

import (
    "fmt"
    "time"
    "strconv"

    //from https://github.com/pplcc/plotext/
    "log"
    "os"

    "github.com/360EntSecGroup-Skylar/excelize"
    "github.com/pplcc/plotext/custplotter"
    "gonum.org/v1/plot"
    "github.com/pplcc/plotext"
    "gonum.org/v1/plot/vg/vgimg"
    "gonum.org/v1/plot/vg/draw"
)

    // Len implements the Len method of the TOHLCVer interface.
    func (TOHLCV TOHLCVs) Len() int {
        return len(TOHLCV)

func main() {

//read excel file******************************************
    xlsx, err := excelize.OpenFile("/media/Snaps/test snaps.xlsm")
    if err != nil {
        fmt.Println(err)
        return
    }

    //read all rows into df
    df := xlsx.GetRows("ticker_2")

    type TOHLCVer interface {
        // Len returns the number of time, open, high, low, close, volume tuples.
        Len() int

        // TOHLCV returns an time, open, high, low, close, volume tuple.
        TOHLCV(int) (float64, float64, float64, float64, float64, float64)
    }

    type TOHLCVs []struct{ T, O, H, L, C, V float64 }

    // Len implements the Len method of the TOHLCVer interface.
    func (TOHLCV TOHLCVs) Len() int {
        return len(TOHLCV)
    }

    df3 := make(TOHLCVs, 60) // create slice for 60 rows
    idx := 0

此代码改编自: https ://github.com/pplcc/plotext/blob/master/custplotter/tohlcv.go

标签: gostructslice

解决方案


函数声明需要从其他函数中移出,如下所示

package main

import (
    "fmt"

    "github.com/360EntSecGroup-Skylar/excelize"
)

type TOHLCVer interface {
    // Len returns the number of time, open, high, low, close, volume tuples.
    Len() int

    // TOHLCV returns an time, open, high, low, close, volume tuple.
    TOHLCV(int) (float64, float64, float64, float64, float64, float64)
}

type TOHLCVs []struct{ T, O, H, L, C, V float64 }

// Len implements the Len method of the TOHLCVer interface.
func (TOHLCV TOHLCVs) Len() int {
    return len(TOHLCV)
}

func main() {
    //read excel file******************************************
    xlsx, err := excelize.OpenFile("/media/Snaps/test snaps.xlsm")
    if err != nil {
        fmt.Println(err)
        return
    }

    //read all rows into df
    df := xlsx.GetRows("ticker_2")

    df3 := make(TOHLCVs, 60) // create slice for 60 rows
    idx := 0
}

类型声明可以在函数内部。但是,在这种情况下,他们在外面更有意义。在某些情况下,在另一个函数中声明一个函数会很有帮助:

(我不确定您正在寻找的确切逻辑 - 上面的代码还没有做任何事情。我也会警告不要创建接口,除非您需要它。)


推荐阅读