From 3fb83e16aa3fe711f8bac58e6642e842583c43e8 Mon Sep 17 00:00:00 2001 From: tfrench Date: Thu, 1 Aug 2024 19:50:19 +0000 Subject: [PATCH] give guidance to reduce scope of constants --- src/var-scope.md | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/var-scope.md b/src/var-scope.md index 362b651e..fb36ee4b 100644 --- a/src/var-scope.md +++ b/src/var-scope.md @@ -1,6 +1,6 @@ -# Reduce Scope of Variables +# Reduce Scope of Variables and Constants -Where possible, reduce scope of variables. Do not reduce the scope if it +Where possible, reduce scope of variables and constants. Do not reduce the scope if it conflicts with [Reduce Nesting](nest-less.md). @@ -66,3 +66,36 @@ return nil
+ +Avoid making constants global unless they are used in multiple functions. + + + + + +
BadGood
+ +```go +const ( + _defaultPort = 8080 + _defaultUser = "user" +) + +func Bar() { + fmt.Println("Default port", _defaultPort) +} +``` + + + +```go +func Bar() { + const ( + defaultPort = 8080 + defaultUser = "user" + ) + fmt.Println("Default port", _defaultPort) +} +``` + +