diff --git a/accounts/abi/abigen/bindv2.go b/accounts/abi/abigen/bindv2.go index ce9bda3bc9..caf87d5823 100644 --- a/accounts/abi/abigen/bindv2.go +++ b/accounts/abi/abigen/bindv2.go @@ -276,7 +276,7 @@ func parseLibraryDeps(unlinkedCode string) (res []string) { // onItem on each. If the callback returns an error, iteration is halted and // the error is returned from iterSorted. func iterSorted[V any](inp map[string]V, onItem func(string, V) error) error { - var sortedKeys []string + sortedKeys := make([]string, 0, len(inp)) for key := range inp { sortedKeys = append(sortedKeys, key) } diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go index e48f763890..85649a05f0 100644 --- a/accounts/abi/argument.go +++ b/accounts/abi/argument.go @@ -62,7 +62,7 @@ func (argument *Argument) UnmarshalJSON(data []byte) error { // NonIndexed returns the arguments with indexed arguments filtered out. func (arguments Arguments) NonIndexed() Arguments { - var ret []Argument + ret := make([]Argument, 0, len(arguments)) for _, arg := range arguments { if !arg.Indexed { ret = append(ret, arg) diff --git a/accounts/abi/bind/v2/generate_test.go b/accounts/abi/bind/v2/generate_test.go index c9ca3e6038..3fa6247359 100644 --- a/accounts/abi/bind/v2/generate_test.go +++ b/accounts/abi/bind/v2/generate_test.go @@ -41,7 +41,7 @@ import ( // mutations to the binding code. func TestBindingGeneration(t *testing.T) { matches, _ := filepath.Glob("internal/contracts/*") - var dirs []string + dirs := make([]string, 0, len(matches)) for _, match := range matches { f, _ := os.Stat(match) if f.IsDir() { @@ -50,12 +50,6 @@ func TestBindingGeneration(t *testing.T) { } for _, dir := range dirs { - var ( - abis []string - bins []string - types []string - libs = make(map[string]string) - ) basePath := filepath.Join("internal/contracts", dir) combinedJsonPath := filepath.Join(basePath, "combined-abi.json") abiBytes, err := os.ReadFile(combinedJsonPath) @@ -67,6 +61,10 @@ func TestBindingGeneration(t *testing.T) { t.Fatalf("Failed to read contract information from json output: %v", err) } + abis := make([]string, 0, len(contracts)) + bins := make([]string, 0, len(contracts)) + types := make([]string, 0, len(contracts)) + libs := make(map[string]string, len(contracts)) for name, contract := range contracts { // fully qualified name is of the form : nameParts := strings.Split(name, ":") diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index 8b06c8477d..41231954a9 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -45,9 +45,7 @@ func TestPack(t *testing.T) { if err != nil { t.Fatalf("invalid ABI definition %s, %v", inDef, err) } - var packed []byte - packed, err = inAbi.Pack("method", test.unpacked) - + packed, err := inAbi.Pack("method", test.unpacked) if err != nil { t.Fatalf("test %d (%v) failed: %v", i, test.def, err) } diff --git a/accounts/manager.go b/accounts/manager.go index aafb93af96..1e8ece706a 100644 --- a/accounts/manager.go +++ b/accounts/manager.go @@ -65,7 +65,7 @@ type Manager struct { // supported backends. func NewManager(config *Config, backends ...Backend) *Manager { // Retrieve the initial list of wallets from the backends and sort by URL - var wallets []Wallet + wallets := make([]Wallet, 0, len(backends)) for _, backend := range backends { wallets = merge(wallets, backend.Wallets()...) } diff --git a/bmt/bmt.go b/bmt/bmt.go index 96209519f9..70a7c30510 100644 --- a/bmt/bmt.go +++ b/bmt/bmt.go @@ -218,7 +218,7 @@ func (t *Tree) Draw(hash []byte, d int) string { hashes = append(hashes, []string{"", fmt.Sprintf("%v", hashstr(hash)), ""}) total := 60 del := " " - var rows []string + rows := make([]string, 0, len(hashes)+2) for i := len(hashes) - 1; i >= 0; i-- { var textlen int hash := hashes[i] diff --git a/cmd/XDC/config.go b/cmd/XDC/config.go index c151fdf634..a5afdc06d4 100644 --- a/cmd/XDC/config.go +++ b/cmd/XDC/config.go @@ -229,7 +229,7 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend, XDCConfig) { // Create gauge with geth system and build information if eth != nil { // The 'eth' backend may be nil in light mode - var protos []string + protos := make([]string, 0, len(eth.Protocols())) for _, p := range eth.Protocols() { protos = append(protos, fmt.Sprintf("%v/%d", p.Name, p.Version)) } diff --git a/consensus/XDPoS/XDPoS.go b/consensus/XDPoS/XDPoS.go index ad4de98365..66c621afd2 100644 --- a/consensus/XDPoS/XDPoS.go +++ b/consensus/XDPoS/XDPoS.go @@ -218,8 +218,8 @@ func (x *XDPoS) VerifyHeaders(chain consensus.ChainReader, headers []*types.Head // Split the headers list into v1 and v2 buckets var v1headers []*types.Header var v2headers []*types.Header - var v1fullVerifies []bool - var v2fullVerifies []bool + v1fullVerifies := make([]bool, 0, len(headers)) + v2fullVerifies := make([]bool, 0, len(headers)) for i, header := range headers { switch x.config.BlockConsensusVersion(header.Number) { diff --git a/consensus/XDPoS/engines/engine_v2/forensics.go b/consensus/XDPoS/engines/engine_v2/forensics.go index 22b68c610d..5fbdd698f5 100644 --- a/consensus/XDPoS/engines/engine_v2/forensics.go +++ b/consensus/XDPoS/engines/engine_v2/forensics.go @@ -274,7 +274,7 @@ func (f *Forensics) findQCsInSameRound(quorumCerts1 []types.QuorumCert, quorumCe // Find the signer list from QC signatures func (f *Forensics) getQcSignerAddresses(quorumCert types.QuorumCert) []string { - var signerList []string + signerList := make([]string, 0, len(quorumCert.Signatures)) // The QC signatures are signed by votes special struct VoteForSign quorumCertSignedHash := types.VoteSigHash(&types.VoteForSign{ diff --git a/consensus/XDPoS/utils/pool.go b/consensus/XDPoS/utils/pool.go index 8792503b7b..2e3ea31b4f 100644 --- a/consensus/XDPoS/utils/pool.go +++ b/consensus/XDPoS/utils/pool.go @@ -74,7 +74,7 @@ func (p *Pool) PoolObjKeysList() []string { p.lock.RLock() defer p.lock.RUnlock() - var keyList []string + keyList := make([]string, 0, len(p.objList)) for key := range p.objList { keyList = append(keyList, key) } diff --git a/consensus/XDPoS/utils/utils.go b/consensus/XDPoS/utils/utils.go index 0b40983da3..6af811ad15 100644 --- a/consensus/XDPoS/utils/utils.go +++ b/consensus/XDPoS/utils/utils.go @@ -38,8 +38,8 @@ func ExtractValidatorsFromBytes(byteValidators []byte) ([]int64, error) { return []int64{}, fmt.Errorf("invalid byte array length %d for validators", len(byteValidators)) } lenValidator := len(byteValidators) / M2ByteLength - var validators []int64 - for i := 0; i < lenValidator; i++ { + validators := make([]int64, 0, lenValidator) + for i := range lenValidator { trimByte := bytes.Trim(byteValidators[i*M2ByteLength:(i+1)*M2ByteLength], "\x00") intNumber, err := strconv.ParseInt(string(trimByte), 10, 64) if err != nil { diff --git a/console/console.go b/console/console.go index 7a754e0f84..b6dc490aa5 100644 --- a/console/console.go +++ b/console/console.go @@ -261,7 +261,7 @@ func (c *Console) clearHistory() { // consoleOutput is an override for the console.log and console.error methods to // stream the output into the configured output stream instead of stdout. func (c *Console) consoleOutput(call goja.FunctionCall) goja.Value { - var output []string + output := make([]string, 0, len(call.Arguments)) for _, argument := range call.Arguments { output = append(output, fmt.Sprintf("%v", argument)) } diff --git a/contracts/utils.go b/contracts/utils.go index 0a858f9209..6ce761e993 100644 --- a/contracts/utils.go +++ b/contracts/utils.go @@ -275,7 +275,7 @@ func GenM2FromRandomize(randomizes []int64, lenSigners int64) ([]int64, error) { // Get validators from m2 array integer. func BuildValidatorFromM2(listM2 []int64) []byte { - var validatorBytes []byte + validatorBytes := make([]byte, 0, len(listM2)*utils.M2ByteLength) for _, numberM2 := range listM2 { // Convert number to byte. m2Byte := common.LeftPadBytes(fmt.Appendf(nil, "%d", numberM2), utils.M2ByteLength) diff --git a/contracts/utils_test.go b/contracts/utils_test.go index 60f806dd33..cafeb412ed 100644 --- a/contracts/utils_test.go +++ b/contracts/utils_test.go @@ -166,7 +166,7 @@ func isArrayEqual(a [][]int64, b [][]int64) bool { // Unit test for func TestGenM2FromRandomize(t *testing.T) { - var a []int64 + a := make([]int64, 0, 11) for i := 0; i <= 10; i++ { a = append(a, int64(rand.Intn(9999))) } diff --git a/core/asm/lex_test.go b/core/asm/lex_test.go index e6901d4e37..d578276659 100644 --- a/core/asm/lex_test.go +++ b/core/asm/lex_test.go @@ -24,7 +24,7 @@ import ( func lexAll(src string) []token { ch := Lex("test.asm", []byte(src), false) - var tokens []token + tokens := make([]token, 0, len(ch)) for i := range ch { tokens = append(tokens, i) } diff --git a/core/rawdb/database.go b/core/rawdb/database.go index 8d5ee008ba..4c27e0552c 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -39,7 +39,7 @@ type freezerdb struct { // Close implements io.Closer, closing both the fast key-value store as well as // the slow ancient tables. func (frdb *freezerdb) Close() error { - var errs []error + errs := make([]error, 0, 2) if err := frdb.AncientStore.Close(); err != nil { errs = append(errs, err) } diff --git a/core/state/statedb_test.go b/core/state/statedb_test.go index ef1a93878e..24854dd7ee 100644 --- a/core/state/statedb_test.go +++ b/core/state/statedb_test.go @@ -356,7 +356,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction { }, } action := actions[r.Intn(len(actions))] - var nameargs []string + nameargs := make([]string, 0, 1+len(action.args)) if !action.noAddr { nameargs = append(nameargs, addr.Hex()) } diff --git a/core/state_processor.go b/core/state_processor.go index 48251abcde..4092114f06 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -68,7 +68,7 @@ func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consen // transactions failed to execute due to insufficient gas it will return an error. func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, tradingState *tradingstate.TradingStateDB, cfg vm.Config, tokensFee map[common.Address]*big.Int) (types.Receipts, []*types.Log, uint64, error) { var ( - receipts types.Receipts + receipts = make([]*types.Receipt, 0, len(block.Transactions())) usedGas = new(uint64) header = block.Header() blockHash = block.Hash() diff --git a/core/types/hashing.go b/core/types/hashing.go index 76f7069191..b065f9d78f 100644 --- a/core/types/hashing.go +++ b/core/types/hashing.go @@ -92,7 +92,7 @@ func DeriveSha(list DerivableList, hasher TrieHasher) common.Hash { // StackTrie requires values to be inserted in increasing hash order, which is not the // order that `list` provides hashes in. This insertion sequence ensures that the // order is correct. - var indexBuf []byte + indexBuf := make([]byte, 0, list.Len()) for i := 1; i < list.Len() && i <= 0x7f; i++ { indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(i)) value := encodeForDerive(list, i, valueBuf) diff --git a/core/types/transaction.go b/core/types/transaction.go index 5ba445fa6a..2d697548ad 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -608,7 +608,7 @@ func (s Transactions) EncodeIndex(i int, w *bytes.Buffer) { func TxDifference(a, b Transactions) (keep Transactions) { keep = make(Transactions, 0, len(a)) - remove := make(map[common.Hash]struct{}) + remove := make(map[common.Hash]struct{}, len(b)) for _, tx := range b { remove[tx.Hash()] = struct{}{} } @@ -626,7 +626,7 @@ func TxDifference(a, b Transactions) (keep Transactions) { func HashDifference(a, b []common.Hash) []common.Hash { keep := make([]common.Hash, 0, len(a)) - remove := make(map[common.Hash]struct{}) + remove := make(map[common.Hash]struct{}, len(b)) for _, hash := range b { remove[hash] = struct{}{} } diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index d2ceba92aa..cb1c6baa51 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -127,11 +127,11 @@ func NewEVMInterpreter(evm *EVM) *EVMInterpreter { default: table = &frontierInstructionSet } - var extraEips []int if len(evm.Config.ExtraEips) > 0 { // Deep-copy jumptable to prevent modification of opcodes in other tables table = copyJumpTable(table) } + extraEips := make([]int, 0, len(evm.Config.ExtraEips)) for _, eip := range evm.Config.ExtraEips { if err := EnableEIP(eip, table); err != nil { // Disable it, so caller can check if it's activated or not diff --git a/internal/build/file.go b/internal/build/file.go index 2d8c993f36..4525f94776 100644 --- a/internal/build/file.go +++ b/internal/build/file.go @@ -85,7 +85,7 @@ func HashFolder(folder string, exlude []string) (map[string][32]byte, error) { // DiffHashes compares two maps of file hashes and returns the changed files. func DiffHashes(a map[string][32]byte, b map[string][32]byte) []string { - var updates []string + updates := make([]string, 0, len(a)+len(b)) for file := range a { if _, ok := b[file]; !ok || a[file] != b[file] { diff --git a/metrics/prometheus/collector.go b/metrics/prometheus/collector.go index 1d49f51dc2..524ba1f83b 100644 --- a/metrics/prometheus/collector.go +++ b/metrics/prometheus/collector.go @@ -140,7 +140,7 @@ func (c *collector) writeGaugeInfo(name string, value metrics.GaugeInfoValue) { c.buff.WriteString(fmt.Sprintf(typeGaugeTpl, name)) c.buff.WriteString(name) c.buff.WriteString(" ") - var kvs []string + kvs := make([]string, 0, len(value)) for k, v := range value { kvs = append(kvs, fmt.Sprintf("%v=%q", k, v)) } diff --git a/metrics/registry.go b/metrics/registry.go index 6070f3d0e9..2254160538 100644 --- a/metrics/registry.go +++ b/metrics/registry.go @@ -49,8 +49,8 @@ type orderedRegistry struct { // Each call the given function for each registered metric. func (r *orderedRegistry) Each(f func(string, interface{})) { - var names []string reg := r.registered() + names := make([]string, 0, len(reg)) for name := range reg { names = append(names, name) } diff --git a/node/rpcstack.go b/node/rpcstack.go index 6605036e27..472b5e6701 100644 --- a/node/rpcstack.go +++ b/node/rpcstack.go @@ -179,7 +179,7 @@ func (h *httpServer) start() error { ) // Log all handlers mounted on server. - var paths []string + paths := make([]string, 0, len(h.handlerNames)) for path := range h.handlerNames { paths = append(paths, path) } diff --git a/trie/sync_test.go b/trie/sync_test.go index 3b594bde45..2e7502fd8e 100644 --- a/trie/sync_test.go +++ b/trie/sync_test.go @@ -384,7 +384,7 @@ func TestDuplicateAvoidanceSync(t *testing.T) { // The code requests are ignored here since there is no code // at the testing trie. paths, nodes, _ := sched.Missing(0) - var elements []trieElement + elements := make([]trieElement, 0, len(paths)) for i := 0; i < len(paths); i++ { elements = append(elements, trieElement{ path: paths[i],