8000 staticcheck: flag string(T) where T is a newtype of uint8 that has a String() method · Issue #1119 · dominikh/go-tools · GitHub
[go: up one dir, main page]

Skip to content

staticcheck: flag string(T) where T is a newtype of uint8 that has a String() method #1119

Open

Description

@ainar-g

(Filing separately from #682, since this is something outside of go vet's check; feel free to merge.)

package main

import "fmt"

type newtype uint8

func (v newtype) String() (s string) { return "newtype" }

func main() {
	// Example A
	fmt.Println(string(64))

	// Example B
	fmt.Println(string(newtype(64)))

	// Example C
	fmt.Println(newtype(64).String())
}

go vet will mark example A but not example B, probably because it still allows string(byte) conversions and thinks that newtype is the same as byte.

staticcheck (as of v0.3.0-0.dev.0.20211107063326-8cad455d2ffe) doesn't report any errors. There is already an issue about reproducing the original go vet check, but I think that this one is different, because this one concerns newtypes, and in particular ones that have their own String() method. I think that if the programmer (1) defined a new type and (2) added a String() method for it then it is extremely unlikely that they would want string(T) as opposed to T.String() anywhere in their code.

(Also, apologies for opening a blank issue instead of using a template. A force of habit 😅.)

Activity

  1. added
    aggressiveA set of checks that is more prone to false positives but is helpful during code review
    needs-decisionWe have to decide if this check is feasible and desirable
    on Nov 10, 2021
  2. dominikh commented on Nov 10, 2021

    @dominikh
    Owner

    Marking as aggressive because I'm not sure this would fit into staticcheck, and marking as needs-decision because I'm not sure it fits at all. I can imagine valid code that would do this, for example in the context of binary serialization. The type would represent some field in a binary file format, its String method returns a human-friendly representation (such as the name of an enum), and string(b) would be used while building output to write. It's somewhat far-fetched, however, because binary serialization shouldn't be using strings.

  3. added this to the Staticcheck 2022.2 milestone on Jan 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    aggressiveA set of checks that is more prone to false positives but is helpful during code reviewneeds-decisionWe have to decide if this check is feasible and desirablenew-check

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0