🌊

Goでshould merge variable declaration with assignment on next lineが出た時

2023/01/09に公開

interfaceに関する記事を書く際、vscodeのlinterで下記のように注意書きが表示された。

should merge variable declaration with assignment on next line (S1021)

ソースコードはこんな感じ

package main

import "fmt"

type Shape interface {
  Area() int
}

type Circle struct {
  width  int
  height int
}

func (c *Circle) Area() int {
  return c.width * c.height
}

func main() {

  var shape Shape // 警告が出た箇所
  shape = &Circle{
    width:  3,
    height: 4,
  }

  fmt.Println(shape.Area())
}

修正するときは宣言時と代入を一緒にやればOK。

package main

import "fmt"

type Shape interface {
  Area() int
}

type Circle struct {
  width  int
  height int
}

func (c *Circle) Area() int {
  return c.width * c.height
}

func main() {

  // 代入をまとめて書きばいい。
  var shape Shape = &Circle{
    width:  3,
    height: 4,
  }

  fmt.Println(shape.Area())
}

Discussion